Why “('a' in arr) in arr” != “'a' in arr in arr”? [duplicate]

删除回忆录丶 提交于 2020-04-28 09:13:08

问题


Why is ('a' in arr) in arr != 'a' in arr in arr?

arr = [1, True, 'a', 2]
print(('a' in arr) in arr)  # -> True
print('a' in arr in arr)  # -> False

回答1:


Section 6.10 of the Python language reference discusses comparison operators and comparison chaining. in is considered a comparison operator, and so behaves the same as <, etc. Without parentheses for explicit grouping, x OP1 y OP2 zis equivalent to x OP1 y and y OP2 z for any two comparison operators.

This means that

'a' in arr in arr

without parentheses, is equivalent to

'a' in arr and arr in arr

arr is not an element of itself, so the expression is False.

Parentheses disable chaining, so

('a' in arr) in arr

is evaluated like any other nested expression. 'a' in arr is evaluated first to the value True, then True in arr is evaluated to also produce True.




回答2:


I might be wrong, but I think that in is like any binary operator, so just like you have a < b < c equivalent to (a < b) and (b < c) , you will have

a in b in c

equivalent to

(a in b) and (b in c)

'a' in arr is True, but arr in arr is False, that's why you have a False value.




回答3:


Given arr=[1,True,'a',2],

Decoding first expression: ('a' in arr) in arr,

step-by-step

  • ('a' in arr) in arr evaluates to

  • (True) in [1,True,'a',2] evaluates to

  • True

Decoding second expression: ('a' in arr in arr)

step-by-step

  • ('a' in arr in arr) This is equivalent to
  • ('a' in arr and arr in arr) which evaluates to
  • (True and False) which evaluates to
  • (False)

More on: Precedence and associative nature https://www.programiz.com/python-programming/precedence-associativity



来源:https://stackoverflow.com/questions/60400708/why-a-in-arr-in-arr-a-in-arr-in-arr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!