Search code examples
pythontry-catchnonetype

TypeError: 'NoneType' object is not iterable when overwriting old value


This is a simplification of my program, I have a hard time understanding why the error occurs and what the solution to it is.

def test(n=0):


 a = [];
 b = [];

 if n == 0:
  return a,b
 else:
  a.append(1);
  b.append(2);


for i in range(0,2):
 x,y = test(i)

x and y must have different values at each iteration, but since the function returns None at one point and then later it wants to overvwrite it , it will get crash with the error "TypeError" - is there a clean solution, despite using some kind of try - catch machnism?

The following code makes the program run, but it feels like misusing the try-catch mechanism of an earlier design error.

def test(n=0):


 a = [];
 b = [];

 if n == 0:
  return a,b
 else:
  a.append(1);
  b.append(2);


for i in range(0,2):
 try:
  x,y = test(i)
 except TypeError:
  continue;

Solution

  • Your function test has no return in such a case function automatically return None, while on return you are trying to put returned[0] to x and returned[1] to y. Where as returned is None which is not iterable.

    Correct Code :

    def test(n=0):
    
    
     a = [];
     b = [];
    
     if n == 0:
      return a,b
     else:
      a.append(1);
      b.append(2);
    
    return a,b
    
    for i in range(0,2):
     x,y = test(i)