Check if list is empty without using the `not` command
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
I am very much a beginner so excuse me if I do dumb mistakes.
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"
检查它的长度。
l = []
print len(l) == 0
链接地址: http://www.djcxy.com/p/22504.html
上一篇: 为什么在Python中没有明确的空白检查(例如`Empty')
下一篇: 检查列表是否为空而不使用`not`命令