I've been writing a lot of constructs like this the past couple of days:
things = get_list()
if things:
for i in things:
pass # do something with the list
else:
pass # do something if the list was empty
Lot of junk and I assign the list to a real variable (keeping it in memory longer than needed). Python has simplified a lot of my code up til now... Is there a easy way to do this?
(My understanding is that the else
in the for ... else:
construct always triggers after it has looped, empty or not - so not what I want)
Use a list comprehension:
def do_something(x):
return x**2
things = []
result = [do_something(x) for x in things]
print result # []
things = [1, 2, 3]
result = [do_something(x) for x in things]
print result # [1, 4, 9]