Retrieving a specific object from a list?
Terry Reedy
tjreedy at udel.edu
Thu Apr 9 13:06:28 EDT 2009
Jeremiah Dodds wrote:
> 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?
for x in items:
if x.baz == some_other_value: break
More information about the Python-list
mailing list