What is the most Pythonic way to find all Nones in a list of lists?

Viewed 52

Is there a better Pythonic way to find all Nones in a list of lists than this code?

    def find_nones_locations(lst):
         none_locations = []
         for i in range(len(lst)):
              for j in range(len(lst)):
                   if lst[i][j] is None:
                        none_locations.append((i,j))
         return none_locations
2 Answers

You can use a list comprehension to do it in one shot, but I'm not sure it's necessarily better than a legible loop:

none_locations = [(i, j) for i, row in enumerate(lst) for j, elem in enumerate(row) if elem is None]

Nested loops in comprehensions follow the same order they do in plain code. There's no good reason not to use a plain loop:

none_locations = []
for i, row in enumerate(lst):
    for j, elem in enumerate(row):
        if elem is None:
            none_locations.append((i, j))

The only potential improvement over your code is the use of the enumerate generator. Any time you need both the index and the value of an iterable, that's generally the pythonic way to get it.

You can use enumerate to clean up the code a bit:

def find_nones_locations(lst):
     none_locations = []
     for i, sublst in enumerate(lst):
          for j, item in enumerate(sublist):
               if item is None:
                    none_locations.append((i,j))
     return none_locations
Related