Scherf Scherf - 1 year ago 51
Python Question

Use and meaning of "in" in an if statement in python

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.

Answer Source

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, 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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download