How is the __contains__ method of the list class in Python implemented?

前端 未结 3 854
感动是毒
感动是毒 2020-12-19 12:30

Suppose I define the following variables:

mode = \"access\"
allowed_modes = [\"access\", \"read\", \"write\"]

I currently have a type check

3条回答
  •  感情败类
    2020-12-19 12:40

    No, they're not equivalent. For example:

    >>> mode = float('nan')
    >>> allowed_modes = [mode]
    >>> any(mode == allowed_mode for allowed_mode in allowed_modes)
    False
    >>> mode in allowed_modes
    True
    

    See Membership test operations for more details, including this statement:

    For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y).

提交回复
热议问题