Suppose I define the following variables:
mode = "access"
allowed_modes = ["access", "read", "write"]
I currently have a type checking statement which is
assert any(mode == allowed_mode for allowed_mode in allowed_modes)
However, it seems that I can replace this simply with
assert mode in allowed_modes
According to ThiefMaster's answer in Python List Class __contains__ Method Functionality, these two should be equivalent. Is this indeed the case? And how could I easily verify this by looking up Python's source code?
Python string __contains__() is an instance method and returns boolean value True or False depending on whether the string object contains the specified string object or not. Note that the Python string contains() method is case sensitive.
__ contains __ method is used to overload the “in” operator in python. For example, you have a custom class MyClass and you want to check if one instance is in another by using it. What is this? In such case you'll use the contains a method to overload this “in” operator.
Like all special methods (with "magic names" that begin and end in __ ), __contains__ is not meant to be called directly (except in very specific cases, such as up=calls to the superclass): rather, such methods are called as part of the operation of built-ins and operators.
List. Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
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 toany(x is e or x == e for e in y)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With