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.

Answer from agf on Stack Overflow
🌐
Bobby Hadz
bobbyhadz.com › blog › python-find-object-in-list-of-objects
Find object(s) in a List of objects in Python | bobbyhadz
To find all objects in a list that meet a condition: Use a list comprehension to iterate over the list. Check if each object has an attribute that meets a condition.
Discussions

Get list item by attribute in Python - Stack Overflow
I need to load a list of database row objects into memory, and then grab one of those rows by its unique ID. Is there a clean, pythonic way of finding an single object from a list by an attribute v... More on stackoverflow.com
🌐 stackoverflow.com
python - How do i access and object attribute inside a list of objects given certain index? - Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... and you do so in python as well, but how exactly you get a certain attribute at a certain index in a list of objects... More on stackoverflow.com
🌐 stackoverflow.com
Searching a list of objects in Python - Stack Overflow
Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... You don’t understand DNS like you think you... Dispatches from O'Reilly: From capabilities to... ... -2 How can I extract two values from a list of lists in Python, where the sublist begins with a specific number? 166 Check if list of objects contain an object with a certain attribute ... More on stackoverflow.com
🌐 stackoverflow.com
flask - How to find object in python list by attribute - Stack Overflow
Stack Data Licensing Get access ... & attributed content. Stack Ads Connect your brand to the world’s most trusted technologist communities. Releases Keep up-to-date on features we add to Stack Overflow and Stack Internal. ... pythonjavascriptc#reactjsjavaandroidhtmlflutterc++node.jstypescriptcssrphpangularnext.jsspring-bootmachine-learningsqlexceliosazuredocker ... Next You’ll be prompted to create an account to view your personalized homepage. Find centralized, ... More on stackoverflow.com
🌐 stackoverflow.com
May 26, 2019
People also ask

What is the best way to find objects in a list in Python?
A: The best method often depends on your specific use case. For single lookups, using next with a generator expression is efficient. If you need multiple matches, converting the list to a dictionary might offer the best performance.
🌐
sqlpey.com
sqlpey.com › python › top-8-ways-to-find-an-object-in-a-list-by-attribute-value-in-python
Top 8 Ways to Find an Object in a List by Attribute Value in Python
Can I find multiple objects using one of these methods?
A: Yes, methods like list comprehension will return a list of all matching items, while converting your list to a dictionary allows for quick lookups of unique items.
🌐
sqlpey.com
sqlpey.com › python › top-8-ways-to-find-an-object-in-a-list-by-attribute-value-in-python
Top 8 Ways to Find an Object in a List by Attribute Value in Python
Is there a performance difference between the methods?
A: Yes, methods that utilize dictionaries for lookups tend to be faster for multiple queries compared to list comprehensions or iterative approaches, especially with large datasets.
🌐
sqlpey.com
sqlpey.com › python › top-8-ways-to-find-an-object-in-a-list-by-attribute-value-in-python
Top 8 Ways to Find an Object in a List by Attribute Value in Python
🌐
Reddit
reddit.com › r/learnpython › how do i find the first object in a list of objects that has a specified desired attribute
r/learnpython on Reddit: How do I find the first object in a list of objects that has a specified desired attribute
February 25, 2022 -

Hey, so I'm coding up a discord bot, where I have a list of Objects (discord.CategoryChannel() is the class)

all these objects have an attribute 'name' which is a string

I need to return the object who's 'name' attribute is 'Temp VCs'

I have figured out that I can use any() to find if such an object exists in the list whose 'name' is 'Temp VCs'

However what method can I use (apart from the brute force way of writing a for loop and an if statement inside it) to return the object which has its attribute 'name' equal to 'Temp VCs'

🌐
GeeksforGeeks
geeksforgeeks.org › get-index-in-the-list-of-objects-by-attribute-in-python
Get index in the list of objects by attribute in Python - GeeksforGeeks
December 19, 2021 - We don't need to import additional libraries to utilize the enumerate() function because it's built-in to Python. If we use enumerate function() then we don't have to worry about making a range() statement and then retrieving the length of an array.
🌐
EyeHunts
tutorial.eyehunts.com › home › python find object in list | example code
Python find object in list | Example code - Tutorial - By EyeHunts
June 13, 2022 - import random class Test: def ....randint(0, 100)) for x in range(300)] def find(val): for x in test_list: if x.value == val: print("Found it!") break else: x = None return find(value) ......
🌐
GeeksforGeeks
geeksforgeeks.org › python › searching-a-list-of-objects-in-python
Searching a list of objects in Python - GeeksforGeeks
July 23, 2025 - In this article, we will look at ways to find objects in a list of objects in Python. ... We have provided multiple examples to search objects in a list of objects in Python. Create a class Car with the following attributes and perform a search operation that returns cars with a price less than 10 Lakhs (10,00,000/-).
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › article › get-index-in-the-list-of-objects-by-attribute-in-python
Get index in the list of objects by attribute in Python
March 27, 2026 - def find_index_by_attribute(obj_list, attr_name, attr_value): """Find index of object by attribute value""" for i, obj in enumerate(obj_list): if getattr(obj, attr_name) == attr_value: return i return None class Student: def __init__(self, name, ...
🌐
sqlpey
sqlpey.com › python › top-8-ways-to-find-an-object-in-a-list-by-attribute-value-in-python
Top 8 Ways to Find an Object in a List by Attribute Value in Python
November 1, 2024 - You can also employ list comprehension to retrieve the first item that meets your criteria. object_found = [x for x in objects if x["id"] == 1][0] print(object_found) # Output: {'id': 1, 'name': 'ronaldo'} Creating a custom function is another effective approach if you seek clarity and reusability. def find_object_by_id(arr, id): for obj in arr: if obj["id"] == id: return obj result = find_object_by_id(objects, 1) print(result) # Output: {'id': 1, 'name': 'ronaldo'}
🌐
Iditect
iditect.com › faq › python › get-index-in-the-list-of-objects-by-attribute-in-python.html
Get index in the list of objects by attribute in Python
class MyClass: def __init__(self, ... find object index in list by attribute value" Description: This query aims to locate the index of an object within a list by matching a specific attribute value in Python....
🌐
Reddit
reddit.com › r/python › get attributes from a 2d list (or array) of objects?
r/Python on Reddit: Get attributes from a 2D list (or array) of objects?
October 3, 2015 -

I have a rather simple question but I haven't been able to find an answer so far: if I have a 2D list of objects, how can I extract all the values from a common attribute?

This is some class:

class Foo():
    def __init__(self, attr):
        self.attr = attr

For a 1D list, it's really simple:

array = [Foo(i) for i in range(6)]
[obj.attr for obj in array]

This will display: [0, 1, 2, 3, 4, 5].

For a multidimensional list, though, this won't work. A solution would be using loops or lists of comprehension to extract the attributes from each column or line. However, slices allow us to access a specific region of a multidimensional list.

So, let's say you have a 6x6 list (or ndarray) of objects, and you want to access the attributes at [4:,4:], or even better, you want to slice the list in a non-contiguous way and then get the attributes of all object elements in the pattern. Is that possible?

Check this image from the numpy docs to have a visual reference about what I'm talking about (see 2nd and 4th slices).

I'm aiming at being able to use this for a board game in which the board would be sliced into different "tile" groups or patterns and then check the properties of the objects in those tiles.

This is not homework.

Top answer
1 of 4
21

One option is to use the next() built-in:

dave = next(person for person in a.pList if person.num == 123)

This will throw StopIteration if nothing is found. You can use the two-argument form of next() to provide a default value for that case:

dave = next(
    (person for person in a.pList if person.num == 123),
    None,
)

A slightly more verbose alternative is a for loop:

for person in a.pList:
    if person.num == 123:
        break
else:
    print "Not found."
    person = None
dave = person
2 of 4
7

If those nom's are unique keys, and all you are ever going to do is access your persons using this unique key you should indeed rather use a dictionary.

However if you want to add more attributes over time and if you like to be able to retrieve one or more person by any of those attributes, you might want to go with a more complex solution:

class Example():
    def __init__(self):
        self.__pList = []
    def addPerson(self,name,number):
        self.__pList.append(Person(name,number))
    def findPerson(self, **kwargs):
        return next(self.__iterPerson(**kwargs))
    def allPersons(self, **kwargs):
        return list(self.__iterPerson(**kwargs))
    def __iterPerson(self, **kwargs):
        return (person for person in self.__pList if person.match(**kwargs))

class Person():
    def __init__(self,name,number):
        self.nom = name
        self.num = number
    def __repr__(self):
        return "Person('%s', %d)" % (self.nom, self.num) 
    def match(self, **kwargs):
        return all(getattr(self, key) == val for (key, val) in kwargs.items())

So let's assume we got one Mike and two Dave's

a = Example()
a.addPerson('dave',123)
a.addPerson('mike',345)
a.addPerson('dave',678)

Now you can find persons by number:

>>> a.findPerson(num=345)
Person('mike', 345)

Or by name:

>>> a.allPersons(nom='dave')
[Person('dave', 123), Person('dave', 678)]

Or both:

>>> a.findPerson(nom='dave', num=123)
Person('dave', 123)
🌐
TutorialsPoint
tutorialspoint.com › python-get-the-object-with-the-max-attribute-value-in-a-list-of-objects
Python - Get the object with the max attribute value in a list of objects
July 18, 2023 - In the below example, we define a Person class with name and age attributes. We create a list of Person objects called person_list. By using the max() function and providing the key parameter as a lambda function that returns the age attribute of each Person object, we can find the person with ...
🌐
Medium
medium.com › data-science › searching-or-sorting-a-list-of-objects-based-on-an-attribute-in-python-6cffb26a57c3
Searching or Sorting a list of Objects Based on an Attribute in Python | by Allison Stafford | TDS Archive | Medium
April 29, 2020 - Today, we’ll look at Python’s built in tool for doing just this: operator.attrgetter, as well as the related tools in this toolkit and alternate methods to achieve similar goals (using lambdas and iterators/comprehensions). ... For our data set today, we’re going to be using a fictional data set of a pack of 100 dogs. The dog student class has attributes: name, yr, strengths, areas_for_growth, works_well_with, not_works_well_with, has_sat_by, has_not_sat_by, and notes.
Top answer
1 of 4
1

To handle the last element, you can use modulo: index % len(users).

Here is one way:

def find_after_name(users, name):
    for i, user in enumerate(users):
        if user.name == name:
            return users[(i+1) % len(users)]

Another option would be to zip the list with a shifted copy of the list. deque.rotate() is useful for such shifting:

from collections import deque
def find_after_name(users, name):
    users2 = deque(users)
    users2.rotate(-1)
    for user1, user2 in zip(users1, users2):
        if user1.name == name:
            return user2
2 of 4
1

Since you've chosen to use OOP, why not implement a UserList class inherited from built-in list class?

class User(object):
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return repr(self)

    def __repr__(self):
        return "User('{0}')".format(self.name)


class UserList(list):
    def find(self, name):
        for k, user in enumerate(self):
            if user.name == name:
                return k, user

    def next_to(self, name):
        """get user next to the one of name (e.g. 'James')"""
        index, user = self.find(name)
        next_to_index = self.get_next_to_index(index)
        return self[next_to_index]

    def get_next_to_index(self, index):
        next_to_index = index + 1
        if next_to_index == len(self):
            # meaning index is already the last element, need to reset index
            next_to_index = 0
        return next_to_index


users = UserList()
users.append(User("Peter"))
users.append(User("James"))
users.append(User("John"))

print users.find('James')
print users.next_to('James')
print users.next_to('John')

Output:

(1, User('James'))
User('John')
User('Peter')