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?

1

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

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

Comments

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

Comments

Your Answer

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