+ 3

list operations

nums=[1,2,3,4] print(4 not in nums) print(not 4 in nums) -------------------------------- here NOT and IN both are list operators.... which one is going to execute first....... not or in?

16th Jan 2019, 7:45 AM
Asish Addanki
Asish Addanki - avatar
5 Answers
+ 9
Usually membership operators don't have any precedence. in and not in are different operators thus print (4 not in nums) is obviously False as 4 is in nums print(not 4 in nums ) would work like print(not True) {since 4 in nums is True } ; which gives us False https://www.tutorialspoint.com/python/operators_precedence_example.htm Interesting question tho.. a second opinion would be better.
16th Jan 2019, 7:57 AM
Frost - avatar
+ 4
In your first case, "not in" is an operator in its own right. So it checks if the element is not part of the list. In the second case the operators are independent, and the execution order is deternined by operator precedence. "in" is evaluated first, resulting True, then not True = False is printed. More info: http://www.informit.com/articles/article.aspx?p=459269&seqNum=11
16th Jan 2019, 7:52 AM
Tibor Santa
Tibor Santa - avatar
+ 4
Here's the official list of operator precedence in Python: https://docs.python.org/3/reference/expressions.html#operator-precedence I'm sharing this because it differs a little from the other two (though both of them explain this particular case correctly).
16th Jan 2019, 1:08 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 1
print (not 4un nums) would work like print (not true)
17th Feb 2019, 6:25 PM
Khojo Afful
In python when we use not and in simultaneously even have some int in between they are treated as single keyword... Therefore in this case both have same precedence...
17th Jan 2019, 3:06 PM
Rohit - avatar