Nane
Nane

Reputation: 153

Python 'in' operator with 'for' loop and with 'if' statement

I am using python in operator with for loop and with if statement. My question is how is in implemented, that it behaves differently in this two cases: it iterates when using for loop and it checks if some element exists when using with if statement? Does this depend on implementation of for and if?

    for i in x:
        #iterates

    if i in x:
        #checks weather i in x or not 

Upvotes: 5

Views: 12820

Answers (5)

JMAA
JMAA

Reputation: 2049

In many languages you'll find keywords that have multiple uses. This is simply an example of that. It's probably more helpful to think in terms of statements than thinking about the in keyword like an operator.

The statement x in y is a boolean-valued statement taking (assuming y is some appropriate collection) True if and only if the value of x is in the collection y. It is implemented with the __contains__ member function of y.

The statement for x in y: starts a loop, where each iteration x takes a different value from the collection y. This is implemented using the __iter__ member function of y and __next__ on the resulting iterator object.

There are other statements where the in keyword can appear, such as list comprehension or generator comprehension.

Upvotes: 1

Sven-Eric Krüger
Sven-Eric Krüger

Reputation: 1317

Membership testing with in is implemented via the method __contains__ (see Documentation). The different behaviour comes from the keyword before, for and if in your case.

Iteration with for is implemented such, that the method next is called and its return value is written to the iteration variable as long as the condition after the key word for is true. Membership testing in general is just a condition.

Code

A in B

Execution

B.__contains__(A)  # returns boolean

Code

for A in B :
    # Body

Execution

A = B.next()
if B.__contains__(A) :
    # Body

A = B.next()
if B.__contains__(A) :
    # Body

# ...

A = B.next()
if B.__contains__(A) :
    # B.next() throws "StopIteration" if there is no more element

Upvotes: 2

MisterMiyagi
MisterMiyagi

Reputation: 50076

The in keyword is an operator usually:

print(2 in [1, 2, 3])  # True
if 3 in range(7, 20):
   print('3 in range!')

It corresponds to the object.__contains__ special method. The expression a in b corresponds to type(b).__contains__(a). Note that both a and b are names that are looked up.

In a for statement, in is not an operator. It is part of the for .. in .. syntax and separates the loop variable name from the iterable.

for thing in range(20):
    print(thing)  # thing is something else on each step

Note that for a in b only b is a name that is looked up. a is a name to bind to, similar to an assignment statement.


Python syntax has several constructs where the leading keyword defines the meaning of following keywords. For example, the as keyword has a different meaning in import and with:

# as aliases ExitStack
from contextlib import ExitStack as ContextStack

# as holds the result of ContextStack().__enter__()
with ContextStack() as stack:
    ...

It helps to think about such keywords not by implementation but by meaning. For example, a in b always means that "a is contained by b".

Upvotes: 0

gireesh4manu
gireesh4manu

Reputation: 109

The keyword "in" in python solves different purposes based on "for" and "if". please look at this related link in stack overflow for more clarity

Upvotes: 1

BoarGules
BoarGules

Reputation: 16942

The reason is that for...in is something different from just in.

for x in y iterates over y.

if x in y calls y.__contains__(x).

Upvotes: 0

Related Questions