Sunday, April 17, 2011

Sweet Python Syntax

I've been writing Python code for quite a while, yet sometimes I still get surprised by some neat undiscovered feature. This is what I found today. The neat part is where the tuple is unpacked inplace in the for statement.

things = {}
things[1] = (2,3)
things[2] = (4,5)

for id, (A, B) in things.items():
print id, A, B

I could be wrong, but I vaguely recall trying this once, and it not working. Now it does!

6 comments:

Anonymous said...

Works for years like this... ;)

Franklin said...

And you can use the new unpacking sintax available in Python 3.x

things = {}
things[0] = (1,2,3)

for id, (a, *b) in things.items():
print(id, a, b)

John M said...

other variations:

- explicitly ignore an arg using the "_" variable. This is most useful when you're using the 2nd and 5th args inside a packed row of data.

for _, (a,b) in things.items():
dostuff

Since you're not using the keys, don't ask for them. Also itervalues() fetches one item at a time, vs making a huge list.

for (a,b) in things.itervalues():
dostuff

Brandon Craig Rhodes said...

I just tested this under Python 1.5 and it worked perfectly. Just how long ago did you try this and find that it did not work? :)

Simon Wittber said...

LOL, please note these words from my post, "Vaguely" and "Could be wrong" :-)

Anonymous said...

imo people should use that a lot more because otherwise they do arcane workarounds to get the same resuls; more examples: http://goo.gl/jyrIn

Popular Posts