-1

How to find a None in a nested listed. When I run the following code, the Hello is not printed. I do not know how to spot a None in the list of a list. Can you please help me with this simple question.

myList = [[0,1,2],[5,None,300]]

if None in myList:

print("Hello")
CypherX
  • 7,019
  • 3
  • 25
  • 37
Daan
  • 5
  • 1
  • 1
    I would expect if the indentation is really like this that you'd get an error on that if statement. – mauve Oct 29 '19 at 19:40
  • 1
    Are you just trying to find this, or did you need the data manipulated in some way as well? – Fallenreaper Oct 29 '19 at 19:42
  • As the answers are pointing out, you need to iterate over a list inside your myList - "for list in myList", and then check for None in the resultant 'list'. – jhelphenstine Oct 29 '19 at 19:44
  • Thanks a lot for the solutions! I was using the right indendation but I did not know how to iterate over list of lists. – Daan Oct 31 '19 at 13:40

4 Answers4

4

This is basically a special case of How to make a flat list out of list of lists?; you need to flatten it to perform the test. In this case, the best approach is to use itertools.chain to do the flattening, which allows you to use the in testing in a short-circuiting manner (it stops when it finds a None, no work is done for elements after it):

from itertools import chain

myList = [[0,1,2],[5,None,300]]

if None in chain.from_iterable(myList):
    print("Hello")
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
4

You could use any:

myList = [[0,1,2],[5,None,300]]
if any(None in l for l in myList):
    print("Hello")

Or itertools.chain:

from itertools import chain
if None in chain(*myList):
    print("Hello")
Jab
  • 26,853
  • 21
  • 75
  • 114
1

Please, pay attention to indentation:

for inner_list in myList:
   for item in inner_list:
      if item is None:
         print('hello')
rok
  • 9,403
  • 17
  • 70
  • 126
0
myList = [[0,1,2],[5,None,300]]

for x in myList:
    if None in x:
        print("Hello")

Note that this will print once for every "None" found.

Mefitico
  • 816
  • 1
  • 12
  • 41