4

I have a nested list and I want to check if an item has a value or not.

Not really sure how to describe it, so basically, how do I get this to work?

list = [ [item1, a, b], [item2, a, b], [item3, a] ]

if list[2][2] #is empty (has no value):
    print("There is no value at list[2][2]!")
else:
    print("There is a value at list[2][2]")
Quint van Dijk
  • 303
  • 2
  • 12
  • 3
    A list is boolean False if it's empty. So you could do 'if list[2]' or check len(list[2]) to see how many entries it has. By the way 'list' is a reserved word, you should better use some other variable name. – djangonaut Sep 28 '15 at 20:49
  • 3
    http://stackoverflow.com/questions/53513/best-way-to-check-if-a-list-is-empty – midori Sep 28 '15 at 20:49
  • `if len(L) > 2 and len(L[2]) > 2:`. – ekhumoro Sep 28 '15 at 20:54
  • 1
    See what error happens when you try to access list[2][2], then catch that error using Python's exception handling mechanism. Also, avoid using variable names that are in the Python built-ins, like 'list'. – Chad Kennedy Sep 28 '15 at 21:00
  • "if list[2]" gives me an "IndexError: list index out of range" error. But the "len(list[2]" idea does work, Thanks! – Quint van Dijk Sep 28 '15 at 21:04
  • 1
    In general it's better to create your lists to be homogeneous. That is, each item in the list behaves like the other items. It's not required, but to do otherwise makes for much more complicated programs. – Chad S. Sep 28 '15 at 21:07
  • what's wrong with the `IndexError`? can't you just `catch` it? (see @dallen's answer) – umläute Sep 28 '15 at 21:35
  • @ChadSimmons agreed. This looks like it should be a list of tuples to me. – Adam Smith Sep 28 '15 at 21:48

2 Answers2

4

Here's an example using EAFP (Easier to ask for forgiveness than permission). It is a very common coding pattern in python that assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false.

try:
    item = list[2][2]
except IndexError:
    print 'There is no value at list[2][2]'
else:
    print '{} is at list[2][2]'.format(item)
Diego Allen
  • 4,623
  • 5
  • 30
  • 33
0

Just loop through your list of sublist either using for-loop or while-loop, simultaneously check whether it has elements or not and print them. Hope this helps. Thanks

list = [[1, 2, 5], [2, 3, 7], ['', 'stack', 'overflow']]
i = 0
j = 0
while i<3:
    j = 0
    while j<3:
        print list[i][j]
        if list[i][j] == '':
            print "Has no element at", i, ",", j
            break
        else:
            print "has elements"
            j += 1
    i += 1

print "Successfully checked"