Check if list is empty without using the `not` command
In order of preference:
# 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 elements
else:
# list is empty
You find out if a list is empty by testing the 'truth' of it:
>>> bool([])
False
>>> bool([0])
True
While in the second case 0
is False, but the list [0]
is True because it contains something. (If you want to test a list for containing all falsey things, use all or any: any(e for e in li)
is True if any item in li
is truthy.)
This results in this idiom:
if li:
# li has something in it
else:
# optional else -- li does not have something
if not li:
# react to li being empty
# optional else...
According to PEP 8, this is the proper way:
• For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
Yes: if not seq: if seq: No: if len(seq) if not len(seq)
You test if a list has a specific index existing by using try
:
>>> try:
... li[3]=6
... except IndexError:
... print 'no bueno'
...
no bueno
So you may want to reverse the order of your code to this:
if list3:
print list3
else:
print "No matches found"