views:

75

answers:

3

I'm new to python and haven't yet read a lot of code to verify which styles are considered 'pythonic'.

As I've started to code, I've been using this pattern alot.

listThatMightBeEmpty = []
for items in listThatMightBeEmpty:
    print "this may or may not print but the loop won't cause any errors"

I assume that it would be redundant to first check if the list is empty - that I can just let the for-in loop do nothing if the list is empty. But I want to make sure there aren't any gotchas for any situation including using old versions of python, and including using a for-in loop on dictionaries, using enumerate(), or iteritems(), or using list comprehensions etc.

+2  A: 

Yes you are right. There are no gotchas here. You can use it on an empty list.

pyfunc
+1  A: 

To check whether a list is empty, you can do this:

>>> x = []
>>> if not x:
         # do something

If the list is empty, # do something will run and you can handle the execution there.

However, there is nothing wrong with your approach.

sukhbir
+1  A: 

Yes it is redundant (unless you want to perform something special for empty input).

In general, the for loop and and function that return another thing that you can iterate on will not give any "surprising behaviors" if you have an input of zero items. This includes enumerate() , iteritems(), and even slicing ([][1:] == []).

>>> list( enumerate([]) )
[]
>>> list( {}.iteritems() )
[]
>>> [][1:]
[]
>>> [x*x for x in []]
[]
KennyTM