Check if list of objects contain an object with a certain attribute value
Question:
I want to check if my list of objects contain an object with a certain attribute value.
class Test:
def __init__(self, name):
self.name = name
# in main()
l = []
l.append(Test("t1"))
l.append(Test("t2"))
l.append(Test("t2"))
I want a way of checking if list contains an object with name "t1"
for example. How can it be done? I found https://stackoverflow.com/a/598415/292291,
[x for x in myList if x.n == 30] # list of all 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
I don’t want to go through the whole list every time; I just need to know if there’s 1 instance which matches. Will first(...)
or any(...)
or something else do that?
Answers:
As you can easily see from the documentation, the any()
function short-circuits an returns True
as soon as a match has been found.
any(x.name == "t2" for x in l)
Another built-in function next()
can be used for this job. It stops at the first instance where the condition is True
much like any()
.
next((True for x in l if x.name=='t2'), False)
Also, next()
can return the object itself where the condition is True
(so behaves like first()
function in the OP).
next((x for x in l if x.name == 't2'), None)
I want to check if my list of objects contain an object with a certain attribute value.
class Test:
def __init__(self, name):
self.name = name
# in main()
l = []
l.append(Test("t1"))
l.append(Test("t2"))
l.append(Test("t2"))
I want a way of checking if list contains an object with name "t1"
for example. How can it be done? I found https://stackoverflow.com/a/598415/292291,
[x for x in myList if x.n == 30] # list of all 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
I don’t want to go through the whole list every time; I just need to know if there’s 1 instance which matches. Will first(...)
or any(...)
or something else do that?
As you can easily see from the documentation, the any()
function short-circuits an returns True
as soon as a match has been found.
any(x.name == "t2" for x in l)
Another built-in function next()
can be used for this job. It stops at the first instance where the condition is True
much like any()
.
next((True for x in l if x.name=='t2'), False)
Also, next()
can return the object itself where the condition is True
(so behaves like first()
function in the OP).
next((x for x in l if x.name == 't2'), None)