Unlike in some laguages, empty
is not a keyword in Python. Python lists are constructed form the ground up, so if element i
has a value, then element i-1
has a value, for all i > 0
.
To do an equality check, you usually use either the ==
comparison operator.
>>> my_list = ["asdf", 0, 42, '', None, True, "LOLOL"]
>>> my_list[0] == "asdf"
True
>>> my_list[4] is None
True
>>> my_list[2] == "the universe"
False
>>> my_list[3]
""
>>> my_list[3] == ""
True
Here's a link to the strip
method: your comment indicates to me that you may have some strange file parsing error going on, so make sure you're stripping off newlines and extraneous whitespace before you expect an empty line.
Just check if that element is equal to None type or make use of NOT operator ,which is equivalent to the NULL type you observe in other languages.
if not A[i]:
## do whatever
Anyway if you know the size of your list then you don't need to do all this.
If you want to know if list element at index i
is set or not, you can simply check the following:
if len(l)<=i:
print ("empty")
If you are looking for something like what is a NULL-Pointer or a NULL-Reference in other languages, Python offers you None
. That is you can write:
l[0] = None # here, list element at index 0 has to be set already
l.append(None) # here the list can be empty before
# checking
if l[i] == None:
print ("list has actually an element at position i, which is None")
Try:
if l[i]:
print 'Found element!'
else:
print 'Empty element.'
I got around this with len()
and a simple if/else
statement.
List elements will come back as an integer when wrapped in len()
(1 for present, 0 for absent)
l = []
print(len(l)) # Prints 0
if len(l) == 0:
print("Element is empty")
else:
print("Element is NOT empty")
Output:
Element is empty
Suppose
letter= ['a','','b','c']
for i in range(len(letter)):
if letter[i] =='':
print(str(i) + ' is empty')
output- 1 is emtpy
So we can see index 1 is empty.
Source: Stackoverflow.com