python中判断列表元素是否为空
1、
>>> a = []
>>> b = ["aa","bb","cc"]
>>> if len(a) == 0:
print("empty!")
empty!
>>> if len(b) == 0:
print("empty!")
2、
>>> a = ["aa","bb","cc","dd"]
>>> for i in a:
print(i)
else:
print("empty!")
aa
bb
cc
dd
empty!
>>> if a: ## 需要加if a
for i in a:
print(i)
else:
print("empty!")
aa
bb
cc
dd
>>> a = []
>>> for i in a:
print(i)
else:
print("empty!")
empty!
>>> if a: ## 正确
for i in a:
print(i)
else:
print("empty!")
empty!
3、
>>> a = ["aa","bb","cc","dd"]
>>> if len(a) != 0:
for i in a:
print(i)
else:
print("empty!")
aa
bb
cc
dd
>>> a = []
>>> if len(a) != 0:
for i in a:
print(i)
else:
print("empty!")
empty!