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!
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

srav
Courses Plus Student 3,476 Pointswhen to use in/not in/is/is not in Python ??
Hi,
I came across these terms( in/not in/is/is not ) and am a bit confused between them. Not sure if I understand them correctly. Could any one shed some light on them. plss ??
2 Answers

Alexander Davison
65,469 PointsFirst let's cover in
/not in
.
in
is an easy way to check if an element is in a list or not. not in
is similar, but instead it checks if an element is not in a list.
>>> my_list = [1, 2, 3]
>>> 0 in my_list
False
>>> 1 in my_list
True
>>> 0 not in my_list
True
is
/is not
is a little more difficult to understand.
is
is similar to ==
, but it checks for exact equivalence. ==
checks if all of the attributes of one object and all of the methods of one object is equal to all of the attributes and methods of another.
But, is
checks if two objects are exactly equivalent. This means that the memory location (aka ID) must be equal too.
>>> 1 is 1
True
>>> "abc" is "abc"
True
>>> a = 1
>>> b = 1
>>> a == b
True
>>> a is b
True
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a == b
True
>>> a is b
False
Python is pretty memory-efficient, so every time you make a number/string/boolean, it points to the same location in memory. However, with lists, every time you make a new list, it actually does make a brand new list and assigns the value to its own place in memory.
1 ----> 4481526416
^
/
/
/
1 -
4481526416
is a location in memory. Both times you refer to 1
it points to that location in memory.
[1, 2, 3] -----> 4444834184
[1, 2, 3] -----> 4444832776
Lists are less efficient. When you make a list, it links it to a new location in memory.
Therefore [1, 2, 3] is [1, 2, 3]
is False
and 1 is 1
is True
!
I hope this wasn't too technical for you! is
is a more advanced keyword, so don't worry if you don't quite understand it.
Just make you understand in
, and you're fine.

srav
Courses Plus Student 3,476 PointsThanks for the response. Its clear to me now !!