+ 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

7th Sep 2019, 6:15 AM
Edophokles
Edophokles - avatar
5 Respostas
+ 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
7th Sep 2019, 8:10 AM
HonFu
HonFu - avatar
+ 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"☺
7th Sep 2019, 7:28 AM
Solo
Solo - avatar
+ 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 ;-)
7th Sep 2019, 8:17 AM
Thoq!
Thoq! - avatar
+ 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 ;)
7th Sep 2019, 8:49 AM
Edophokles
Edophokles - avatar
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?
7th Sep 2019, 7:07 AM
Edophokles
Edophokles - avatar