"Find" in list of objects

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Thu Oct 23 04:27:59 EDT 2008


Andreas Müller:
> is there a construct like
> list.find (10, key='ID')

You can create yourself a little convenience function, or you can use
something like the following. First some testing code:

class C:
    def __init__(self, id):
        self.id = id
    def __repr__(self):
        return "<%s>" % self.id
seq = map(C, [1, -5, 10, 3])
print seq

That prints:
[<1>, <-5>, <10>, <3>]

Then you can find the index of all the classes with id = 10:
print [i for i, obj in enumerate(seq) if obj.id == 10]

It returns a [2]. If seq doesn't contain the requires object(s) it
returns an empty list.

Or just the first, working lazily:
print (i for i, obj in enumerate(seq) if obj.id == 10).next()

This time if seq doesn't contain the requires object(s) it raises a
StopIteration exception.

You can of course wrap that into a function, using seq and 10 as
arguments.

Bye,
bearophile



More information about the Python-list mailing list