Back
How can I find out if a list is empty without using the not command?
Here is what I tried:
if list3[0] == []: print "No matches found" else: print list3
if list3[0] == []:
print "No matches found"
else:
print list3
I am very much a beginner, so excuse me if I do dumb mistakes.
In order of preference:
# Goodif not list3:# Okayif len(list3) == 0:# Uglyif list3 == []:# Sillytry: next(iter(list3)) # list has elementsexcept StopIteration: # list is empty
# Good
if not list3:
# Okay
if len(list3) == 0:
# Ugly
if list3 == []:
# Silly
try:
next(iter(list3))
# list has elements
except StopIteration:
# list is empty
If you have both an if and an else you might also re-order the cases:
if list3: # list has elementselse: # list is empty
if list3:
31k questions
32.8k answers
501 comments
693 users