Reputation: 19
I know that this error message TypeError: 'NoneType' object is not iterable
means that some data is None
. However, I am looking through all of my lists and there is no part that has a None
element.
hashTable = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
def printWordsUtil(number, curr, output, n):
if curr == n:
print(output)
return
for i in range(len(hashTable[number[curr]])):
output.append(hashTable[number[curr]][i])
printWordsUtil(number, curr + 1, output, n)
output.pop()
if number[curr] == 0 or number[curr] == 1:
return
def printWords(number, n):
return printWordsUtil(number, 0, [], n)
number = 234
n = len(str(number))
num = list(map(int, str(number)))
result = printWords(num, n)
print("\n".join(str(h) for h in result))
My Output
['a', 'd', 'g']
['a', 'd', 'h']
['a', 'd', 'i']
['a', 'e', 'g']
['a', 'e', 'h']
['a', 'e', 'i']
['a', 'f', 'g']
['a', 'f', 'h']
['a', 'f', 'i']
['b', 'd', 'g']
['b', 'd', 'h']
['b', 'd', 'i']
['b', 'e', 'g']
['b', 'e', 'h']
['b', 'e', 'i']
['b', 'f', 'g']
['b', 'f', 'h']
['b', 'f', 'i']
['c', 'd', 'g']
['c', 'd', 'h']
['c', 'd', 'i']
['c', 'e', 'g']
['c', 'e', 'h']
['c', 'e', 'i']
['c', 'f', 'g']
['c', 'f', 'h']
['c', 'f', 'i']
Traceback (most recent call last):
File "<string>", line 47, in <module>
TypeError: 'NoneType' object is not iterable
I want this TypeError
to be removed.
Upvotes: 0
Views: 3959
Reputation: 9704
As has been pointed out the error is in your printWordsUtil() function = you don't return anything (therefore it returns None), and then printWords() returns that value, and then you try to print that return value when you do print("\n".join(str(h) for h in result)
But you also have made another error : The Error message you got : "TypeError: 'NoneType' object is not iterable" does not mean there is a data elemenet of None in your list: A list can contain a None value and you can iterate over that list that contains None. The error message is saying that you are trying to iterate over a None - it means that your code has something which it is trying to treat as an iterable (in this case it is looping around it), but the iterable itself is None.
Finally - your main loop - there tis a far better way to write it : Instead of :
for i in range(len(hashTable[number[curr]])):
output.append(hashTable[number[curr]][i])
printWordsUtil(number, curr + 1, output, n)
output.pop()
if number[curr] == 0 or number[curr] == 1:
return
It can be more easily written :
for index, item in enumerate(hashTable[number[curr]]):
output.append(item)
printWordsUtil(number, curr + 1, output, n)
output.pop()
if number[curr] == 0 or number[curr] == 1:
return
Using enumerate is far more pythonic than doing range(len(...))
There are other improvements you could do as well - but that is the main one.
Upvotes: 1