Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python is there a function for the "in" operator

Is there any Python function for the "in" operator like what we have for operator.lt, operator.gt, .. I wan't to use this function to do something like:

operator.in(5, [1,2,3,4,5,6])
>> True

operator.in(10, [1,2,3,4,5,6])
>> False
like image 989
alloyoussef Avatar asked Jun 30 '14 14:06

alloyoussef


People also ask

Can you use the IN operator for strings in Python?

The in operator is a membership operator that can be used with strings. 04:01 It's going to return True if the first operand is contained within the second, and it'll return False , otherwise. So, try it out.

Are operators functions in Python?

The Python operator module is one of the inbuilt modules in Python, and it provides us with a lot of functions such as add(x, y), floordiv(x, y) etc., which we can use to perform various mathematical, relational, logical and bitwise operations on two input numbers.

What does := mean in Python?

There is new syntax := that assigns values to variables as part of a larger expression. It is affectionately known as “the walrus operator” due to its resemblance to the eyes and tusks of a walrus.


1 Answers

Yes, use operator.contains(); note that the order of operands is reversed:

>>> import operator
>>> operator.contains([1,2,3,4,5,6], 5)
True
>>> operator.contains([1,2,3,4,5,6], 10)
False

You may have missed the handy mapping table at the bottom of the documentation.

like image 171
Martijn Pieters Avatar answered Sep 30 '22 14:09

Martijn Pieters