Retrieving a specific object from a list?

Jeremiah Dodds jeremiah.dodds at gmail.com
Thu Apr 9 06:42:48 EDT 2009


I've been looking over some of my code, and I've found something I do that
has a bit of a smell to it. I've searched the group and docs, and haven't
found much of anything that solves this particular problem, although I may
just not be searching correctly.

Anyhow, I find that often I'll have a list of objects of some sort that I
want to operate on. Most of the time, I'll want to operate on the entire
list, but sometimes I'll want to operate on just one element, or retrieve
just one element, and I end up with code something like the following:

items = [Foo(), Foo(), ... Foo()]

a_item = [x for x in items if x.bar == some_value][0]
another_item = [x for x in items if x.baz == some_other_value][0]

This doesn't seem correct at all, looping over the entire list to create a
list of one element and then pulling that item out. Any advice?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090409/df914076/attachment.html>


More information about the Python-list mailing list