Testing for empty list
Benjamin Kaplan
benjamin.kaplan at case.edu
Fri Dec 25 00:46:47 EST 2009
On Thu, Dec 24, 2009 at 11:56 PM, Rodrick Brown <rodrick.brown at gmail.com> wrote:
>>>> p=[]
>>>> if p is None:
> ... print 'yes'
> ...
>>>>
> This doesn't work as expected.
That probably means that what you expect is wrong.
>>>p = []
# p is now a list object at a certain location
>>> if p is None:
#check to see if p (a list object with 0 elements) is the same object
as None (a singleton of the NoneType)
#the answer is no it's not, so it doesn't execute what's in there.
there are several ways to check to see if a list is empty:
if not p :
The preferred way, but it doesn't always work the way you want. 0,
False, None, and any object with a len() of 0 evaluate to false.
if len(p) == 0 :
checks to see if p is a collection with 0 elements
if p == [] :
probably the obvious choice to beginners, but it isn't pythonic
because it doesn't allow for duck typing
> --
> [ Rodrick R. Brown ]
> http://www.rodrickbrown.com http://www.linkedin.com/in/rodrickbrown
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
More information about the Python-list
mailing list