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?
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.
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.
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.
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.
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 tox < y and y <= z
, except thaty
is evaluated only once (but in both casesz
is not evaluated at all whenx < y
is found to be false).
So it is equivalent to:
>>> (1 in range(2)) and (range(2) == True)
False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With