You can use len () to determine if the list contains or does not have a value, but this is not smart.
sample.py
list_1 = []
if len(list_1) > 0:
print("list_1 : Not empty")
else:
print("list_1 : empty")
There is a more concise way to call it:
sample.py
list_1 = [] #Prepare an empty list
if list_1:
print("list_1 : Not empty :", list_1)
else:
print("list_1 : empty")
list_1.append(1) #Add value to empty list
if list_1:
print("list_1 : Not empty :", list_1)
else:
print("list_1 : empty")
#Output result
# list_1 : empty
# list_1 : Not empty : [1]
The above if list_1: means "True if any value is included". Very convenient.
In addition, the judgment of True or False by the if statement is as follows. Tuples, lists, and dictionary types can be determined in the same way.
sample.py
empty_1 = ''
empty_2 = ' '
empty_3 = 0
empty_4 = 1
empty_5 = "Hello"
if empty_1:
print(" "" : Not empty")
else:
print(" '' : empty")
if empty_2:
print(" ' ' : Not empty")
else:
print(" ' ' : empty")
if empty_3:
print(" 0 : Not empty")
else:
print(" 0 : empty")
if empty_4:
print(" 1 : Not empty")
else:
print(" 1 : empty")
if empty_5:
print(" Hello : Not empty")
else:
print(" Hello : empty")
#Output result
# '' : empty
# ' ' : Not empty
# 0 : empty
# 1 : Not empty
# Hello : Not empty
that's all
Recommended Posts