Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does x in range(...) == y mean in Python 3? [duplicate]

I just stumbled upon the following line in Python 3.

1 in range(2) == True

I was expecting this to be True since 1 in range(2) is True and True == True is True.

But this outputs False. So it does not mean the same as (1 in range(2)) == True. Furthermore it does not mean the same as 1 in (range(2) == True) which raises an error.

Despite years of experience in Python, I am taken off guard. What is going on?

like image 582
Olivier Melançon Avatar asked Feb 09 '18 23:02

Olivier Melançon


People also ask

What does X for X in range mean in Python?

For x in range(3) simply means, for each value of x in range(3), range(3) = 0,1,2. As it is range(3), the loop is looped three times and at each time, value of x becomes 0, then 1 and then 2. Follow this answer to receive notifications. edited Jul 10, 2019 at 5:25.

What is the X in a for loop Python?

The for loop in Python is used to iterate over a sequence, which could be a list, tuple, array, or string. The program operates as follows: We have assigned a variable, x, which is going to be a placeholder for every item in our iterable object.

What does [:: 1 mean in Python?

If you leave slots empty, there's a default. [:] means: The whole thing. [::1] means: Start at the beginning, end when it ends, walk in steps of 1 (which is the default, so you don't even need to write it). [::-1] means: Start at the end (the minus does that for you), end when nothing's left and walk backwards by 1.

What does [- 1 :] mean in Python?

Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.


1 Answers

This is due to the fact that both operators are comparison operators, so it is being interpreted as operator chaining:

https://docs.python.org/3.6/reference/expressions.html#comparisons

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

So it is equivalent to:

>>> (1 in range(2)) and (range(2) == True)
False
like image 133
juanpa.arrivillaga Avatar answered Oct 19 '22 17:10

juanpa.arrivillaga