carlos
carlos

Reputation: 11

Matching a variable with members of a list in Python?

I want to check if a value of a variable matches (==) with a value of any member of a given list, on a single line

Upvotes: 1

Views: 4097

Answers (2)

manji
manji

Reputation: 47978

use in:

> lst = [1,'r']
> v = 1
> v in lst
True

Upvotes: 6

Katriel
Katriel

Reputation: 123622

EDIT: I'll leave this answer cos generator expressions are useful beasts (especially together with any and all) but if you are just testing for membership in the list then you should use in.


any(var == i for i in my_list)

Explanation:

any is a function which takes an iterable object and returns True if any element of that iterable is True.

The list comprehension [x == i for i in my_list] is a list of boolean values comparing x to each value in the list in turn. If any of them is True then x == i. So if you call any on that list you will get the answer you want.

If you change the [] to () in writing a list comprehension you get a generator object instead, which makes the values one at a time instead of constructing them in memory. And if you are passing a generator expression as the only argument to a function, you can omit the extra set of parentheses, to leave the neat syntax above.

There is also a function all.

Upvotes: 1

Related Questions