71

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
Scherf
  • 1,527
  • 4
  • 16
  • 22
  • 6
    http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange – jramirez Nov 04 '13 at 19:41
  • 2
    It may also help to search Google using operators-- for example, `python "in" operator` gives exactly what you would need in its first few results. – jwarner112 Nov 04 '13 at 19:47
  • 7
    On recent Pythons (2.6+), you should not use `next` as a variable name. You will overwrite the built-in function [next](http://docs.python.org/2/library/functions.html#next) – dawg Nov 04 '13 at 19:47
  • what do you think it might mean if i say `if "whatever" in some_list:` – Joran Beasley Nov 04 '13 at 20:10
  • @abarnert I didn't, I just assumed, based on the function of the code, that it was somehow connected to an 'if' statement. I may be used to javascript but I am in no way an expert in either of these languages – Scherf Nov 04 '13 at 20:51
  • 1
    @Scherf: Well, it's "connected" to an `if` statement in the same way that `>` or any other operator is… and the same way as in JavaScript. – abarnert Nov 04 '13 at 20:53
  • Which is essentially what I was asking about. I understood what its function was but not really what it meant. – Scherf Nov 04 '13 at 21:03
  • Possible duplicate of [How do I test multiple variables against a value?](https://stackoverflow.com/questions/15112125/how-do-i-test-multiple-variables-against-a-value) – Stevoisiak Mar 12 '18 at 18:53

8 Answers8

145

It depends on what next is.

If it's a string (as in your example), then in checks for substrings.

>>> "in" in "indigo"
True
>>> "in" in "violet"
False
>>> "0" in "10"
True
>>> "1" in "10"
True

If it's a different kind of iterable (list, tuple, set, dictionary...), then in checks for membership.

>>> "in" in ["in", "out"]
True
>>> "in" in ["indigo", "violet"]
False

In a dictionary, membership is seen as "being one of the keys":

>>> "in" in {"in": "out"}
True
>>> "in" in {"out": "in"}
False
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
27

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".

utdemir
  • 26,532
  • 10
  • 62
  • 81
  • "If the input contains 1 or 2"; why 1 or 2, and not 1 or 0? And for my own sake 'contains' literally means if the string has either number in it, then the expression is true? – Scherf Nov 04 '13 at 20:59
  • 1
    My mistake, I misread those, of course it should be 1 or 0. Actually, contains checks(for strings), if given string is a substring(as others mentioned). There is two calls there: `if next.__contains__("0") or next.__contains__("1"):`. – utdemir Nov 04 '13 at 21:33
  • 1
    +1: This answer complemenents the accepted one very well. For advanced users, it's better to be told about the implementation details than how to use the implementation. – Jo So Nov 11 '13 at 10:19
15

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.

abarnert
  • 354,177
  • 51
  • 601
  • 671
4

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!

jwarner112
  • 1,492
  • 2
  • 14
  • 29
2

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
jramirez
  • 8,537
  • 7
  • 33
  • 46
2

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

jgranger
  • 264
  • 2
  • 9
  • [`raw_input`](http://docs.python.org/2/library/functions.html#raw_input) is guaranteed to return a `str`, which is iterable, so you don't need to guess whether it's returning an iterable object. – abarnert Nov 04 '13 at 19:55
2

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.

bp14
  • 545
  • 5
  • 10
1

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

Ananta
  • 3,671
  • 3
  • 22
  • 26