I have a list of named tuples:
from collections import namedtupleT = namedtuple('T', ['attr1', 'attr2', 'attr3', 'attr4'])
t1 = T('T1', 1, '1234', 'XYZ')
t2 = T('T2', 2, '1254', 'ABC')
t3 = T('T2', 2, '1264', 'DEF')
l = [t1, t2, t3]
I want to check if an element exists in the list T
where attr1 = 'T2'
.
Checking if the list contains such an element by doing:
any(x for x in l if x.attr1 == 'T2')
only returns the information whether such a namedtuple is in the list or not.
I would like to also pop this namedtuple from the list.
One way of doing it is:
if any(x for x in l if x.attr1 == 'T2'):result = [x for x in l if x.attr1 == 'T2'].pop()
However, I don't like this solution, since I'm looping over the list l
twice.
Is there any better/more-elegant way of doing this?