+ 1
How does operator 'in' work applied twice?
Hi Sololearners, this is my first question, so don't be too harsh. ;) I was wondering why the program list = ['a', True] print('a' in list in list) print(('a' in list) in list) results in False True. What happens in the first print function and why doesn't the double 'in' operator executes each 'in' from left to right as it is in the second print function by default? https://code.sololearn.com/cDg102RLrhep/?ref=app
5 odpowiedzi
+ 5
Conditions like that follow the same rule as stuff like:
a<b<c
It's translated to
a<b and b<c.
So accordingly:
a in b and b in c
+ 3
In the first case, the in operator first checks for the presence of the element "a" in the substring "list" - which is not in the line "list" ☺ it turns out "false", then it checks for the presence of "false" in the line "list".
Example:
list1 = ['a', 'b']
list2 = ['a', True, list1]
print('a' in list1 in list2)
"list1" is a substring of "list2".
P.S: "Both in the first case and in the second, the compiler reads the "in" operator from left to right"☺
+ 3
And pls don't use list as a name because it is already the name for the list constructor. Don't f... up your namespace ;-)
+ 1
Thanks HonFu! I was totally unaware of that. But it clearly makes sense. So, we get:
list in list => False.
Thoq!, I will improve, I promise ;)
0
Thank you, Jay. But I know what happens in the second print function. I was more interested about the first one. Can you explain please why it ends up being False?