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

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

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. Its 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 — its 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 dont break out of the loop.

Since it has not been mentioned just for completion.
The good ol filter to filter your to be filtered elements.

Functional programming ftw.

####### Set Up #######
class X:

    def __init__(self, val):
        self.val = val

elem = 5

my_unfiltered_list = [X(1), X(2), X(3), X(4), X(5), X(5), X(6)]

####### Set Up #######

### Filter one liner ### filter(lambda x: condition(x), some_list)
my_filter_iter = filter(lambda x: x.val == elem, my_unfiltered_list)
### Returns a flippin iterator at least in Python 3.5 and thats what Im on

print(next(my_filter_iter).val)
print(next(my_filter_iter).val)
print(next(my_filter_iter).val)

### [1, 2, 3, 4, 5, 5, 6] Will Return: ###
# 5
# 5
# Traceback (most recent call last):
#   File C:UsersmousavinworkspaceScriptstest.py, line 22, in <module>
#     print(next(my_filter_iter).value)
# StopIteration


# You can do that None stuff or whatever at this point, if you dont like exceptions.

I know that generally in python list comprehensions are preferred or at least
that is what I read, but I dont see the issue to be honest. Of course Python is not an FP language, but Map / Reduce / Filter are perfectly readable and are the most standard of standard use cases in functional programming.

So there you go. Know thy functional programming.

filter condition list

It wont get any easier than this:

next(filter(lambda x: x.val == value,  my_unfiltered_list)) # Optionally: next(..., None) or some other default value to prevent Exceptions

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

A simple example:
We have the following array

li = [{id:1,name:ronaldo},{id:2,name:messi}]

Now, we want to find the object in the array that has id equal to 1

  1. Use method next with list comprehension
next(x for x in li if x[id] == 1 )
  1. Use list comprehension and return first item
[x for x in li if x[id] == 1 ][0]
  1. Custom Function
def find(arr , id):
    for x in arr:
        if x[id] == id:
            return x
find(li , 1)

Output all the above methods is {id: 1, name: ronaldo}

Leave a Reply

Your email address will not be published. Required fields are marked *