Search code examples
pythontypeerroriterablenonetypetry-except

Check for NoneTypes in a list of iterables


I would like to loop over a list of iterables, but with the requirement that some elements could be of type None.

This could look something like this:

none_list = [None, [0, 1]]

for x, y in none_list:
    print("I'm not gonna print anything!")

However, this will prompt TypeError: 'NoneType' object is not iterable.

Currently, I catch the error and deal with the NoneType afterwards. For my use case, this results in a lot of duplicated code as I basically substitute the None values and do the same as initially planned inside the for-loop.

try:
    for x, y in none_list:
        print("I'm not gonna print anything!")
except TypeError:
    print("But I will!")
    # Deal with NoneType here

Question: What‘s the best way to ignore the TypeError and check for None values inside the initial loop?


Solution

  • You can iterate over each item and check for None:

    none_list = [None, [0, 1]]
    for item in none_list:
        if item is None:
            continue
        x, y = item
        print(x, y)
    

    Or you may use list comprehension to eliminate Nones first, then you can iterate over normally:

    list_without_none = [item for item in none_list if item is not None]
    for x, y in list_without_none:
        print(x, y)