What way is the best to check an empty list?
Niklas Norrthon
niklas.norrthon at hotmail.com
Thu Mar 26 03:18:45 EDT 2009
On 26 Mar, 04:31, Steve Holden <st... at holdenweb.com> wrote:
> Stef Mientki wrote:
>
> > Now it would be nice to allow iteration over others too, like None .
> > a = None
> > for item in a :
> > do_something_with_item
>
> To me that makes about as much sense as writing
>
> for x in 1.0:
> print x
>
> and expecting it to print 1.0. Numbers just aren't iterable. Neither is
> None. A TypeError exception is the only appropriate response.
>
I can see a use case for the latter:
def some_function(arg, coll=None):
do_stuff(arg)
for item in coll:
do_more(arg, item)
But that can easily be achieved with the "or" operator as Michiel
Overton notes elsewhere in this thread:
def some_function(arg, coll=None):
do_stuff(arg)
for item in coll or []: # <= Here or is used to make None behave
as an empty collection
do_more(arg, item)
/Niklas Norrthon
More information about the Python-list
mailing list