I have a list like
l = []
How do I check if l[i] is empty?
l[i] = ''
and
l[i] = ""
dont't work.
I have a list like
l = []
How do I check if l[i] is empty?
l[i] = ''
and
l[i] = ""
dont't work.
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")
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
List = []
for item in List:
if len(item.rstrip()) != 0:
# Do whatever you want
This will be useful if you have long string list with some whitespace and you're not considering those list values.
Having a similar issue where a location string needed some pre-testing:
loc_string = "site/building/room//ru" # missing rack
is_ok = True
for i in loc_string.split('/'):
if not i:
is_ok = False
if is_ok:
#perform any action
print(is_ok)
This will return True if all values have data.
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.