Find object(s) in a List of objects in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
7 min

banner

# Table of Contents

  1. Find an object in a List of objects in Python
  2. Check if an object exists in a List of objects in Python
  3. Find an object in a List of objects using a for loop
  4. Find all objects in a List that meet a condition
  5. Find all objects in a List that meet using a for loop
  6. Filter a List of Objects using the filter() function
  7. Check if any object in a list of objects meets a condition

# Find an object in a List of objects in Python

To find an object in a list of objects:

  1. Use a generator expression to iterate over the list.
  2. Check if each object has an attribute that meets a condition.
  3. Use the next() function to return the first matching object.
main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __repr__(self): return self.name alice = Employee('Alice', 100) bob = Employee('Bobbyhadz', 75) carl = Employee('Carl', 75) list_of_objects = [alice, bob, carl] # โœ… Get the first object in a list that meets a condition result = next( (obj for obj in list_of_objects if obj.name == 'Bobbyhadz'), None ) print(result) # ๐Ÿ‘‰๏ธ Bobbyhadz print(result.name) # ๐Ÿ‘‰๏ธ Bobbyhadz print(result.salary) # ๐Ÿ‘‰๏ธ 75

find object in list of objects

The code for this article is available on GitHub
The code sample finds the first object in the list that meets a condition. If you need to find all objects that meet a certain condition in a list, scroll down to the next subheading.

We used a generator expression to iterate over the list of objects.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we check if the current object has a name attribute with a specific value and return the result.

When we pass an iterator to the next() function, the next item in the stream is returned.

We also specified a None default value, which is returned if none of the objects in the list meets the condition.

# Check if object exists in a List of objects in Python

Use the any() function to check if an object exists in a list of objects.

The any() function will return True if the object exists in the list, otherwise False is returned.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __repr__(self): return self.name alice = Employee('Alice', 100) bob = Employee('Bobbyhadz', 75) carl = Employee('Carl', 75) list_of_objects = [alice, bob, carl] if any(obj.name == 'Bobbyhadz' for obj in list_of_objects): # ๐Ÿ‘‡๏ธ this runs print('Object exists in list') else: print('Object does NOT exist in list')

check if object exists in list of objects

The code for this article is available on GitHub

We used the any() function to check if a list of objects contains a specific object.

The any function takes an iterable as an argument and returns True if any element in the iterable is truthy.

main.py
my_list = ['alice', 'bobbyhadz', None, 'carl'] # ๐Ÿ‘‡๏ธ True print(any(item is None for item in my_list))
If the iterable is empty or none of the elements in the iterable are truthy, the any function returns False.

We passed a generator expression to the any() function.

main.py
list_of_objects = [alice, bob, carl] if any(obj.name == 'Bobbyhadz' for obj in list_of_objects): # ๐Ÿ‘‡๏ธ this runs print('Object exists in list') else: print('Object does NOT exist in list')
Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

We check if each object has a name attribute equal to a specific value and return the result.

If the condition is met, the any() function returns True and the if block runs.

If the condition is never met, the object is not contained in the list and the else block runs.

# Find an object in a List of objects using a for loop

This is a three-step process:

  1. Use a for loop to iterate over the list.
  2. Check if each object has an attribute that meets a condition.
  3. Use the break statement to break out of the loop once you find a matching object.
main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __repr__(self): return self.name alice = Employee('Alice', 100) bob = Employee('Bobbyhadz', 75) carl = Employee('Carl', 75) list_of_objects = [alice, bob, carl] match = None for obj in list_of_objects: if obj.name == 'Bobbyhadz': match = obj break print(match) # ๐Ÿ‘‰๏ธ Bobbyhadz if match is not None: print(match.name) # ๐Ÿ‘‰๏ธ Bobbyhadz print(match.salary) # ๐Ÿ‘‰๏ธ 75
The code for this article is available on GitHub

We used a for loop to iterate over the list of objects.

Once we find a matching object, we reassign the match variable and break out of the loop.

The break statement breaks out of the innermost enclosing for or while loop.

# Find all objects in a list that meet a condition

To find all objects in a list that meet a condition:

  1. Use a list comprehension to iterate over the list.
  2. Check if each object has an attribute that meets a condition.
  3. The new list will only contain the matching objects.
main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __repr__(self): return self.name alice = Employee('Alice', 100) bob = Employee('Bobbyhadz', 75) carl = Employee('Carl', 75) list_of_objects = [alice, bob, carl] result = [obj for obj in list_of_objects if obj.salary == 75] print(result) # ๐Ÿ‘‰๏ธ [Bobbyhadz, Carl]

find all objects in list that meet condition

The code for this article is available on GitHub

We used a list comprehension to iterate over the list of objects.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we check if the current object has a salary attribute equal to 75 and return the result.

The new list only contains the objects for which the condition is met.

# Getting a List of the values of a specific Attribute

If you only want to get the value of a specific attribute of the matching objects, return it from the list comprehension.

The list comprehension in the following example only contains the values of the name properties of the matching objects.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __repr__(self): return self.name alice = Employee('Alice', 100) bob = Employee('Bobbyhadz', 75) carl = Employee('Carl', 150) list_of_objects = [alice, bob, carl] filtered_list = [ # ๐Ÿ‘‡๏ธ only return `name` attribute obj.name for obj in list_of_objects if obj.salary > 80 ] print(filtered_list) # ๐Ÿ‘‰๏ธ ['Alice', 'Carl']

get list of values of specific attribute

The code for this article is available on GitHub

We accessed the name attribute in the list comprehension instead of returning the whole matching object.

Alternatively, you can use a for loop.

# Find all objects in a list that meet using a for loop

This is a three-step process:

  1. Use a for loop to iterate over the list.
  2. Check if each object has an attribute that meets a condition.
  3. Append the matching objects to a new list.
main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __repr__(self): return self.name alice = Employee('Alice', 100) bob = Employee('Bobbyhadz', 75) carl = Employee('Carl', 75) list_of_objects = [alice, bob, carl] matches = [] for obj in list_of_objects: if obj.salary == 75: matches.append(obj) print(matches) # ๐Ÿ‘‰๏ธ [Bobbyhadz, Carl]

find all objects in list that meet condition using for loop

We used a for loop to iterate over the list of objects.

On each iteration, we check if the current object has a salary attribute equal to 75 and if the condition is met, we append the object to the matches list.

Here is another example.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __repr__(self): return self.name alice = Employee('Alice', 100) bob = Employee('Bobbyhadz', 75) carl = Employee('Carl', 150) list_of_objects = [alice, bob, carl] filtered_list = [] acceptable_names = ['Alice', 'Carl'] for obj in list_of_objects: if obj.name in acceptable_names: filtered_list.append(obj) print(filtered_list) # ๐Ÿ‘‰๏ธ [Alice, Carl] print(filtered_list[0].name) # ๐Ÿ‘‰๏ธ Alice print(filtered_list[0].salary) # ๐Ÿ‘‰๏ธ 100

We used a for loop to iterate over the list of objects.

On each iteration, we access the name attribute on the current object and check if it is one of the acceptable values.

The in operator tests for membership. For example, x in l evaluates to True if x is a member of l, otherwise, it evaluates to False.

If the condition is met, we append the object to a new list.

The new list only contains the objects that meet the condition.

Alternatively, you can use the filter() function.

# Filter a List of Objects using the filter() function

This is a three-step process:

  1. Pass a lambda function and the list of objects to the filter() function.
  2. The lambda function should access an attribute on the supplied object and check for a condition.
  3. Use the list() class to convert the filter object to a list.
main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __repr__(self): return self.name alice = Employee('Alice', 100) bob = Employee('Bobbyhadz', 75) carl = Employee('Carl', 150) list_of_objects = [alice, bob, carl] filtered_list = list( filter( lambda obj: obj.salary > 80, list_of_objects ) ) print(filtered_list) # ๐Ÿ‘‰๏ธ [Alice, Carl] print(filtered_list[0].name) # ๐Ÿ‘‰๏ธ Alice print(filtered_list[0].salary) # ๐Ÿ‘‰๏ธ 100
The code for this article is available on GitHub

The filter() function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.

The lambda function we passed to the filter() function gets called with each object from the list.

The function accesses the salary attribute on the object, checks if the corresponding value greater than 80 and returns the result.

The last step is to use the list() class to convert the filter object to a list.

# Check if any object in a list of objects meets a condition

Use the any() function to check if any objects in a list of objects meets a condition.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __repr__(self): return self.name alice = Employee('Alice', 100) bob = Employee('Bobbyhadz', 75) carl = Employee('Carl', 150) list_of_objects = [alice, bob, carl] if any(obj.salary > 130 for obj in list_of_objects): # ๐Ÿ‘‡๏ธ this runs print('One or more objects meet the condition') else: print('None of the objects meet the condition')
The code for this article is available on GitHub

The any() function takes an iterable as an argument and returns True if any element in the iterable is truthy.

If the iterable is empty or none of the elements in the iterable are truthy, the any function returns False.

We passed a generator expression to the any() function.

On each iteration, we access the salary attribute on the object and check if its value is greater than 130.

If any of the objects in the list meet the condition, the any() function short-circuits returning True, otherwise, False is returned.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev