list operations | SoloLearn: Learn to code for FREE!

+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?

1/16/2019 7:45:32 AM

Asish Addanki

5 Answers

New Answer

+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.

+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

+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).

+1

print (not 4un nums) would work like print (not true)

-1

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...