4

Take the following code as an example:

a = [['James Dean'],['Marlon Brando'],[],[],['Frank Sinatra']]

n = 0

for i in a:
    print a[n][0]
    n = n + 1

I seem to be getting an error with the index value:

IndexError: list index out of range

How do I skip over the empty lists within the list named a?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Does this answer your question? [How do I check if a list is empty?](https://stackoverflow.com/questions/53513/how-do-i-check-if-a-list-is-empty) – mkrieger1 Apr 09 '22 at 20:49

4 Answers4

6

Simple:

for i in a:
    if i:
        print i[0]

This answer works because when you convert a list (like i) to a boolean in an if statement like I've done here, it evaluates whether the list is not empty, which is what you want.

Sam Estep
  • 12,974
  • 2
  • 37
  • 75
3

You can check if the list is empty or not, empty lists have False value in boolean context -

for i in a:
    if i:
        print a[n][0]
    n = n + 1

Also, instead of using n separately, you can use the enumerate function , which returns the current element as well as the index -

for n, i in enumerate(a):
    if i:
        print a[n][0] # though you could just do - print i[0]
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
0

You could either make a test, or catch the exception.

# Test
for i in a:
    if a[n]:
        print a[n][0]
    n = n + 1

# Exception
for i in a:
    try:
        print a[n][0]
    except IndexError:
        pass
    finally:
        n = n + 1

You could even use the condensed print "\n".join(e[0] for e in a if e) but it's quite less readable.

Btw I'd suggest using using for i, element in enumerate(a) rather than incrementing manually n

d6bels
  • 1,432
  • 2
  • 18
  • 30
0

Reading your code, I assume you try to get the first element of the inner list for every non empty entry in the list, and print that. I like this syntax:

a = [['James Dean'],['Marlon Brando'],[],[],['Frank Sinatra']]
# this filter is lazy, so even if your list is very big, it will only process it as needed (printed in this case)
non_empty_a = (x[0] for x in a if x)

for actor in non_empty_a : print (actor)

As mentioned by other answers, this works because an empty list is converted to False in an if-expression

Ward
  • 2,802
  • 1
  • 23
  • 38