How to check if a nested list matters

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

Not 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]")
+4
source share
2 answers

Here's an example of using EAFP (it's easier to ask forgiveness than permission). This is a very common python coding pattern that assumes valid keys or attributes and throws exceptions if the assumption is 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)
+4
source

for-loop, while-loop, , , . .

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

Source: https://habr.com/ru/post/1609371/


All Articles