0

I would post this in my other thread, but I marked that as solved so I think less people would look at it. I want to say this:

if list1 is empty:
      do this
elif list1 has any value in it:
      do this

How do I word that in python?

4
Contributors
4
Replies
5
Views
10 Years
Discussion Span
Last Post by Matt Tacular
0

I would post this in my other thread, but I marked that as solved so I think less people would look at it. I want to say this:

if list1 is empty:
      do this
elif list1 has any value in it:
      do this

How do I word that in python?

>>> a = []
>>> if a:
... 	print "not empty"
... 
>>> b = ['a']
>>> if b:
... 	print "not empty"
... 
not empty
>>>

or you can use len()

0

or for the literal match,

if not list:  # condition will be True if 'list' is any of 0, [], "", (), etc. 
   do(this)
else:
   do(that)
0

This might be easier to understand ...

# test if list is empty

list1 = []
list2 = [7]

if len(list1) > 0:
    print "list1 is not empty"
else:
    print "list1 is empty"
    
if len(list2) > 0:
    print "list2 is not empty"
else:
    print "list2 is empty"

"""
output =
list1 is empty
list2 is not empty
"""
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.