Fix Python – Find object in list that has attribute equal to some value (that meets any condition)

Question

Asked By – seler

I’ve got a list of objects. I want to find one (first or whatever) object in this list that has an attribute (or method result – whatever) equal to value.

What’s the best way to find it?

Here’s a test case:

class Test:
    def __init__(self, value):
        self.value = value

import random

value = 5

test_list = [Test(random.randint(0,100)) for x in range(1000)]

# that I would do in Pascal, I don't believe it's anywhere near 'Pythonic'
for x in test_list:
    if x.value == value:
        print "i found it!"
        break

I think using generators and reduce() won’t make any difference because it still would be iterating through the list.

ps.: Equation to value is just an example. Of course, we want to get an element that meets any condition.

Now we will see solution for issue: Find object in list that has attribute equal to some value (that meets any condition)


Answer

next((x for x in test_list if x.value == value), None)

This gets the first item from the list that matches the condition, and returns None if no item matches. It’s my preferred single-expression form.

However,

for x in test_list:
    if x.value == value:
        print("i found it!")
        break

The naive loop-break version, is perfectly Pythonic — it’s concise, clear, and efficient. To make it match the behavior of the one-liner:

for x in test_list:
    if x.value == value:
        print("i found it!")
        break
else:
    x = None

This will assign None to x if you don’t break out of the loop.

This question is answered By – agf

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0