Search code examples
pythonfor-loopnonetype

For loop through the list unless empty?


I've been writing a lot of constructs like this the past couple of days:

list = get_list()
if list:
    for i in list:
        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)


Solution

  • Use a list comprehension:

    def do_something(x):
      return x**2
    
    list = []
    result = [do_something(x) for x in list if list]
    print result        # []
    
    list = [1, 2, 3]
    result = [do_something(x) for x in list if list]
    print result       # [1, 4, 9]