[]不是None

[]不是None是一个易错点,用代码来看:

1
2
3
4
5
6
7
aaa = []
print(aaa is True) # 输出False

if (aaa := []): # Python 3.8多了一个类似golang的生命方法,等于"aaa=[] if aaa is True"
print("22222", aaa,aaa is not None)
else:
print("11111",aaa,aaa is None) # 会走到这里

那么判断list是否是一个空集,除了用len之外,是可以直接用True来做的:

1
2
3
4
5
6
7
8
l1 = ["Hire", "the", "top", "1%", "freelancers"]

l2 = []

if l2:
print("list is not empty")
else:
print("list is empty")

或者用bool(),原理一样:

1
2
3
4
5
6
7
8
l1 = ["Hire", "the", "top", "1%", "freelancers"]

l2 = []

if bool(l2):
print("list is empty")
else:
print("list is not empty")

而且注意的是aaa = [None]这样的aaa也不是None,啥样的情况会出现None?比如bbb=aaa.sort(),那么这个bbb就是None

感谢您请我喝咖啡~O(∩_∩)O,如果要联系请直接发我邮箱chenx1242@163.com,我会回复你的
-------------本文结束感谢您的阅读-------------