Python: Fix - TypeError: NoneType object is not iterable


Code:
def print_names(names):
  for name in names:
      print(names)

names = None
print_names(names)
Error trace:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-26-481a76948b73> in <cell line: 6>()
      4 
      5 names = None
----> 6 print_names(names)

<ipython-input-26-481a76948b73> in print_names(names)
      1 def print_names(names):
----> 2   for name in names:
      3       print(names)
      4 
      5 names = None

TypeError: 'NoneType' object is not iterable
TypeError- NoneType object is not iterable

Reason for the TypeError

    As you can see, the names variable is declared as type None, you cannot iterate over None types in Python.


Fix:

    It is better to first check if the type is not None before iterating.

    def print_names(names):
      if(names is None):
        print("Names list is empty...")
      else:
        for name in names:
          print(names)
    
    names = None
    print_names(names)
    Output: Names list is empty...
Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org










Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap