8

I have a list like

l = []

How do I check if l[i] is empty?

l[i] = ''

and

l[i] = ""

dont't work.

6
  • 1
    An empty list is a list with no elements (len(l) == 0). Consider this would be true: l = [""]; l[0] == "" as would l = [None]; l[0] is None. Now, what's the goal/intent? :) Commented Dec 7, 2011 at 7:40
  • This is slightly ambiguous. By "empty" do you mean that the index exists, but is the empty string? Or that it doesn't exist at all, e.g. the number of elements is less than your index? Commented Dec 7, 2011 at 7:41
  • Have you tried the equality comparison operator? Like: l[0] == "" Commented Dec 7, 2011 at 7:42
  • 5
    You can't just say "X didn't work". What was the specific comparison you did? What error did you get? Commented Dec 7, 2011 at 7:44
  • I know that the element l[i] exists, but how do I check if the String is empty? (I also tested l[i] == "" and it don't works.) Commented Dec 7, 2011 at 7:52

9 Answers 9

11

Try:

if l[i]:
    print 'Found element!'
else:
    print 'Empty element.'
Sign up to request clarification or add additional context in comments.

2 Comments

This is The Way.
what is it's zero?
4

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.

Comments

3

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.

Comments

2

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")

Comments

0

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.

5 Comments

Apart from some syntax errors in your answer (fixed), it's a bad idea to teach people to use the is keyword for equality testing. It is used for object identity testing (and nothing else). Otherwise, you're in for some confusion.
My mistake, for some reason I was under the impression that None comparisons used is. Maybe it's something I remembered from PHP or something...
Yes, because there is only one None object, so you use the is operator to explicitly test for object identity.
If I declare l.append(None), l[i] is None would work, but I read out of a file and l.append(linecache.getline(datei, number)) creates a new item but it cannot be proved if it's empty by using "is None".
Then you want the last case where my_list[3] == ''. Hint: did you make to strip newlines and other whitespace with mystring.strip()?
0

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    

1 Comment

python if not l: print("empty") else: print("contains data") Its a bit shorter
0
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.

Comments

0

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.

Comments

0

Lets assume we have an empty str within a list: lst = [1, 2,3 , ""], then check whether the list includes ("", []):

[print("empty") if i in ("",[]) else i for i in lst]

output

empty

You can assign any values to the empty string by replacing print statement with a value assignment

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.