Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 'in' keyword in expression vs. in for loop [duplicate]

I understand what the in operator does in this code:

some_list = [1, 2, 3, 4, 5]
print(2 in some_list)

I also do understand that i will take on each value of the list in this code:

for i in [1, 2, 3, 4, 5]:
    print(i)

I am curious if the in operator used in the for loop is the same as the in operator used in the first code.

like image 729
Novice Avatar asked Jul 05 '16 13:07

Novice


People also ask

What is the best alternative to a for loop in Python?

The map() function is a replacement to a for a loop. It applies a function for each element of an iterable.

What is keyword in for loop Python?

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.

Why for loop is better than while in Python?

For loop allows a programmer to execute a sequence of statements several times, it abbreviates the code which helps to manage loop variables. While loop allows a programmer to repeat a single statement or a group of statements for the TRUE condition. It verifies the condition before executing the loop.

Can we use else keyword with any loop in Python?

In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops.


1 Answers

They are the same concept but not the same operators.

In the print(2 in some_list) example, in is an operator that handles several different situations. The Python docs for the in operator give the details, which I paraphrase as follows: x in y calls y.__contains__(x) if y has a __contains__ member function. Otherwise, x in y tries iterating through y.__iter__() to find x, or calls y.__getitem__(x) if __iter__ doesn't exist. The complexity is to provide consistent membership testing for older code as well as newer code — __contains__ is what you want if you're implementing your own classes.

In the for loop, in is just a marker that separates the loop-index variable from whatever you're looping over. The Python docs for the for loop discuss the semantics, which I paraphrase as follows: whatever comes after in is evaluated at the beginning of a loop to provide an iterator. The loop body then runs for each element of the iterator (barring break or other control-flow changes). The for statement doesn't worry about __contains__ or __getitem__.

Edit @Kelvin makes a good point: you can change the behaviour of in with respect to your own new-style classes (class foo(object)):

  • To change x in y, define y.__contains__().
  • To change for x in y, define y.__iter__().
like image 200
cxw Avatar answered Sep 25 '22 03:09

cxw