Python Abuse 25.11.2003

2003-11-25

Stupid iterable tricks

Since bob posted an interesting tip on using iterables at http://www.pycs.net/bob/weblog/2003/11/24.html#P14 I thought I would share a nice, compact technique I use for getting "The first value from an iterable, or a default value if the iterable is exhausted" pycode:

for value in iterable:
    break
else:
    value = "default"

Since in python, the looping variable "value" leaks out of the for loop, and the unconditional break causes the for loop to end immediately, if the iterable has at least one value, it will be assigned to "value". If the iterable has no items and the for loop runs to completion, the else clause will be entered.

posted at 18:19:28    #    comment []    trackback []
November
MoTuWeThFrSaSu
      1 2
3 4 5 6 7 8 9
10111213141516
17181920212223
24252627282930
Oct Dec

Nothing quite like the smell of abusive python code in the morning.

XML-Image Letterimage

© 2003, Donovan Preston