8

I have a list like

l = []

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

l[i] = ''

and

l[i] = ""

dont't work.

user1081715
  • 109
  • 1
  • 1
  • 4
  • 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? :) –  Dec 07 '11 at 07: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? – Codie CodeMonkey Dec 07 '11 at 07:41
  • Have you tried the equality comparison operator? Like: `l[0] == ""` – rossipedia Dec 07 '11 at 07:42
  • 5
    You can't just say "X didn't work". What was the specific comparison you did? What error did you get? – machine yearning Dec 07 '11 at 07: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.) – user1081715 Dec 07 '11 at 07:52
  • @bdhar that's the way I've done it now. Thanks! – user1081715 Dec 07 '11 at 08:58

8 Answers8

12

Try:

if l[i]:
    print 'Found element!'
else:
    print 'Empty element.'
Growth Mindset
  • 1,135
  • 1
  • 12
  • 28
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.

devsaw
  • 1,007
  • 2
  • 14
  • 28
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.

Nihal
  • 5,262
  • 7
  • 23
  • 41
Umesh
  • 187
  • 1
  • 2
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")
phimuemue
  • 34,669
  • 9
  • 84
  • 115
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    
rdbreak
  • 11
  • 3
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.

darth vader
  • 501
  • 8
  • 11
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.

Riccardo B.
  • 354
  • 2
  • 10
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.

machine yearning
  • 9,889
  • 5
  • 38
  • 51
  • 1
    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](http://stackoverflow.com/questions/8158837/create-two-immutable-objects-with-the-same-value-in-python). – Tim Pietzcker Dec 07 '11 at 07:57
  • 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... – machine yearning Dec 07 '11 at 08:00
  • 4
    Yes, because there is only one `None` object, so you use the `is` operator to explicitly test for object identity. – Tim Pietzcker Dec 07 '11 at 08:02
  • 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". – user1081715 Dec 07 '11 at 08:15
  • Then you want the last case where `my_list[3] == ''`. Hint: did you make to strip newlines and other whitespace with `mystring.strip()`? – machine yearning Dec 07 '11 at 20:37