Last updated: Apr 9, 2024
Reading timeยท7 min

for loopfor loopfilter() functionTo find an object in a list of objects:
next() function to return the first matching object.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

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.
None default value, which is returned if none of the objects in the list meets the condition.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.
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')

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.
my_list = ['alice', 'bobbyhadz', None, 'carl'] # ๐๏ธ True print(any(item is None for item in my_list))
any function returns False.We passed a generator expression to the any() function.
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')
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.
for loopThis is a three-step process:
for loop to iterate over the list.break statement to break out of the loop once you find a matching
object.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
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.
To find all objects in a list that meet a condition:
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]

We used a list comprehension to iterate over the list of objects.
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.
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.
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']

We accessed the name attribute in the list comprehension instead of returning
the whole matching object.
Alternatively, you can use a for loop.
for loopThis is a three-step process:
for loop to iterate over the list.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]

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.
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() functionThis is a three-step process:
filter() function.list() class to convert the filter object to a list.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 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.
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.
Use the any() function to check if any objects in a list of objects meets a
condition.
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 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.
You can learn more about the related topics by checking out the following tutorials: