I have a list like
l = []
How do I check if l[i] is empty?
l[i] = ''
and
l[i] = ""
dont't work.
Try:
if l[i]:
print 'Found element!'
else:
print 'Empty element.'
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")
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.
is keyword for equality testing. It is used for object identity testing (and nothing else). Otherwise, you're in for some confusion.None comparisons used is. Maybe it's something I remembered from PHP or something...None object, so you use the is operator to explicitly test for object identity.my_list[3] == ''. Hint: did you make to strip newlines and other whitespace with mystring.strip()?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
python if not l: print("empty") else: print("contains data") Its a bit shorter
len(l) == 0). Consider this would be true:l = [""]; l[0] == ""as wouldl = [None]; l[0] is None. Now, what's the goal/intent? :)l[0] == ""