[python] Use and meaning of "in" in an if statement?

In an example from Zed Shaw's Learn Python the Hard Way, one of the exercises displays the following code:

next = raw_input("> ")
if "0" in next or "1" in next:
    how_much = int(next)

I'm having a hard time understanding the meaning of in in this statement. I'm used to using if statements, such as in javascript, where the syntax is something like:

var = 5;
if (var > 3) {
    //code  to be executed
}

Is this if / in statement (in python) the same as if() in javascript?

Finding an answer to this has been tricky because the in is such a short string to narrow down an answer via search engine, and I don't know the proper name for its operation.

This question is related to python

The answer is


Since you claim to be used to JavaScript:

The Python in operator is similar to the JavaScript in operator.

Here's some JavaScript:

var d = {1: 2, 3: 4};
if (1 in d) {
    alert('true!');
}

And the equivalent Python:

d = {1: 2, 3: 4}
if 1 in d:
    print('true!')

With objects/dicts, they're nearly identical, both checking whether 1 is a key of the object/dict. The big difference, of course, is that JavaScript is sloppily-typed, so '1' in d would be just as true.

With arrays/lists, they're very different. A JS array is an object, and its indexes are the keys, so 1 in [3, 4, 5] will be true. A Python list is completely different from a dict, and its in operator checks the values, not the indexes, which tends to be more useful. And Python extends this behavior to all iterables.

With strings, they're even more different. A JS string isn't an object, so you will get a TypeError. But a Python str or unicode will check whether the other operand is a substring. (This means 1 in '123' is illegal, because 1 can't be a substring of anything, but '1' in '123' is true.)

With objects as objects, in JS there is of course no distinction, but in Python, objects are instances of classes, not dicts. So, in JS, 1 in d will be true for an object if it has a member or method named '1', but in Python, it's up to your class what it means—Python will call d.__contains__(1), then, if that fails, it tries to use your object as an utterable (by calling its __iter__, and, if that fails, by trying to index it with integers starting from 0).

Also, note that JS's in, because it's actually checking for object membership, does the usual JS method-resolution-order search, while Python's in, because it's checking for keys of a dict, members of a sequence, etc., does no such thing. So, technically, it's probably a bit closer to the hasOwnProperty method than the in operator.


Maybe these examples will help illustrate what in does. It basically translate to Is this item in this other item?

listOfNums = [ 1, 2, 3, 4, 5, 6, 45, 'j' ]

>>> 3 in listOfNums:
>>> True

>>> 'j' in listOfNums:
>>> True

>>> 66 in listOfNums:
>>> False

Here raw_input is string, so if you wanted to check, if var>3 then you should convert next to double, ie float(next) and do as you would do if float(next)>3:, but in most cases


Using a in b is simply translates to b.__contains__(a), which should return if b includes a or not.

But, your example looks a little weird, it takes an input from user and assigns its integer value to how_much variable if the input contains "0" or "1".


You are used to using the javascript if, and I assume you know how it works.

in is a Pythonic way of implementing iteration. It's supposed to be easier for non-programmatic thinkers to adopt, but that can sometimes make it harder for programmatic thinkers, ironically.

When you say if x in y, you are literally saying:

"if x is in y", which assumes that y has an index. In that if statement then, each object at each index in y is checked against the condition.

Similarly,

for x in y

iterates through x's in y, where y is that indexable set of items.

Think of the if situation this way (pseudo-code):

for i in next:
    if i == "0" || i == "1":
        how_much = int(next)

It takes care of the iteration over next for you.

Happy coding!


the reserved word "in" is used to look inside an object that can be iterated over.

list_obj = ['a', 'b', 'c']
tuple_obj = ('a', 1, 2.0)
dict_obj = {'a': 1, 'b': 2.0}
obj_to_find = 'c'
if obj_to_find in list_obj:
    print('Object {0} is in {1}'.format(obj_to_find, list_obj))
obj_to_find = 2.0
if obj_to_find in tuple_obj:
    print('Object {0} is in {1}'.format(obj_to_find, tuple_obj))
obj_to_find = 'b'
if obj_to_find in dict_obj:
    print('Object {0} is in {1}'.format(obj_to_find, dict_obj))

Output:

Object c is in ['a', 'b', 'c']
Object 2.0 is in ('a', 1, 2.0)
Object b is in {'a': 1, 'b': 2.0}

However

cannot_iterate_over = 5.5
obj_to_find = 5.5
if obj_to_find in cannot_iterate_over:
    print('Object {0} is in {1}'.format(obj_to_find, cannot_iterate_over))

will throw

Traceback (most recent call last):
File "/home/jgranger/workspace/sandbox/src/csv_file_creator.py", line 43, in <module>
if obj_to_find in cannot_iterate_over:
TypeError: argument of type 'float' is not iterable

In your case, raw_input("> ") returns iterable object or it will throw TypeError


This may be a very late answer. in operator checks for memberships. That is, it checks if its left operand is a member of its right operand. In this case, raw_input() returns an str object of what is supplied by the user at the standard input. So, the if condition checks whether the input contains substrings "0" or "1". Considering the typecasting (int()) in the following line, the if condition essentially checks if the input contains digits 0 or 1.