Python issue with list (TypeError: 'NoneType' object is not iterable)

Question:

I have a list and I am comparing to check if certain set of values exist in that list and return back true or false.

Given below is what I have tried:

l1 = ['apples,oranges,bananas,pears']   <<- list 1
l2 = ['apples,'tomatoes']               <<- list 2
b2 = set(l1).intersection(l2)       <<- comparing the 2 lists

On performing the above I get an error:

TypeError: 'NoneType' object is not iterable

I believe the above error means there is no data but I know the second list (l2) does have a value. Even if one value in the list matches I would like to get a True flag. Could anyone assist. Thanks

Asked By: scott martin

||

Answers:

You are forgetting quotes, in both the lists.

l1 = ['apples', 'oranges', 'bananas', 'pears']
l2 = ['apples','tomatoes']
b2 = set(l1).intersection(set(l2))

To elaborate, what you are comparing, in your example, are the strings ‘apples,oranges,bananas,pears’, ‘apples’, ‘tomatoes’ (with one quote supplied, else it would not compile). Clearly, the intersection of that sets is a null set. That is what you are getting, imo.

Answered By: anotherone

Create your lists like below:

In [369]: l1 = ['apples','oranges','bananas','pears']
In [357]: l2 = ['apples','tomatoes'] 

And then do the intersection:

In [370]: set(l1).intersection(l2)
Out[370]: {'apples'}
Answered By: Mayank Porwal
TypeError: 'NoneType' object is not iterable

This error occurs when your list is not iterable. That is when you have an empty list and use for loop to iterate over it. There are multiple ways to handle the error, however, the best solution is

If not list:
  print('List object is not iterable as it is empty!!')

But in your case, it’s a human error, which is not using quotes after the word/sentence ends.

l1 = ['apples','oranges','bananas','pears']  
l2 = ['apples','tomatoes']           
b2 = set(l1).intersection(l2)

This should do the trick. 🙂

Answered By: ASHISH RAJ
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.