开发者

Python style: for-in syntax, checking for empty lists and dictionaries

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 sur开发者_StackOverflowe 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.


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

  • Old but still holds good : http://effbot.org/zone/python-list.htm


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.


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 []]
[]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜