Use of Lists, Tupples, or Sets in IF statement.

Chris Angelico rosuav at gmail.com
Mon Mar 14 20:33:07 EDT 2016


On Tue, Mar 15, 2016 at 11:26 AM,  <jj0gen0info at gmail.com> wrote:
> In Python is it possible to comparison-equate a variable to a List, Tupple, or Set and have it return True if the contents of the variable matches an element in the List, Tupple, or Set.
>
> E.g.
>
> x = "apple"
>
> x-list = ["apple", "banana", "peach"]
>
> If x == x-list:
>     print('Comparison is True')
> else:
>     print('Comparison is False')

Yep! What you're looking for is the "membership" operator. It's spelled "in":

>>> x = "apple"
>>> x_list = ["apple", "banana", "peach"]
>>>
>>> if x in x_list:
...     print("That is a fruit.")
... else:
...     print("That is not a fruit.")
...
That is a fruit.
>>> x = "jump"
>>> if x in x_list:
...     print("That is a fruit.")
... else:
...     print("You must be Chell.")
...
You must be Chell.


ChrisA



More information about the Python-list mailing list