Let\'s assume I\'m creating a simple class to work similar to a C-style struct, to just hold data elements. I\'m trying to figure out how to search a list of objects for ob
filter(lambda x: x.n == 5, myList)
You can use in
to look for an item in a collection, and a list comprehension to extract the field you are interested in. This (works for lists, sets, tuples, and anything that defines __contains__
or __getitem__
).
if 5 in [data.n for data in myList]:
print "Found it"
See also:
[x for x in myList if x.n == 30] # list of all matches
[x.n_squared for x in myList if x.n == 30] # property of matches
any(x.n == 30 for x in myList) # if there is any matches
[i for i,x in enumerate(myList) if x.n == 30] # indices of all matches
def first(iterable, default=None):
for item in iterable:
return item
return default
first(x for x in myList if x.n == 30) # the first match, if any