Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Jimmy Otis
3,228 PointsPython in operator confusion-Why is this False?
If I make a list
list = ['blue', 'green', 'yellow', 'orange']
list_two = ['blue', 'green', 'yellow', 'orange', 'red']
list in list_two
False
The return of the in operator in the console is always False. Even if the lists were equal to each other, the result is False. Why is this False??? Thank you!
2 Answers
Joe Smith
1,329 PointsI think the in operator checks each element in the list to see if it can find a match. So
a = [1, 2, 3]
b = [1, 2, 3]
a in b
would give you false because there is no single element in b that is equal to a list [1, 2, 3]. If you did this on the other hand:
a = [1, 2, 3]
b = [7, 8, 9, [1, 2, 3]]
a in b
You get true because b[3] is equal to a.
hamsternation
26,617 PointsWell because the list ['blue', 'green', 'yellow', 'orange'] isn't in list_two.
when you tell python list in list_two you're literally asking if list is in list_two. This would return a true result:
>>>list_two.append(list)
>>>list in list_two
True
But notice list_two is now the following:
>>> list_two
['blue', 'green', 'yellow', 'orange', 'red', ['blue', 'green', 'yellow', 'orange']]
To do what you're trying to do, you can look at set comparisons, by turning lists into sets as follows:
>>>set(list).issubset(list_two)
True
Or I guess you can iterate through the list one by one, then use it with the item in list_two command...
>>> for item in list:
... item in list_two
True
True
True
True
>>>
I hope this helps!
Jimmy Otis
3,228 PointsJimmy Otis
3,228 PointsThanks everyone, I figured it out eventually. So obvious now! :)