Check If Value Exists in Python List of Objects
Last Updated :
14 Jan, 2025
When working with Python, we might need to check whether a specific value exists in a list of objects. This problem often arises when dealing with data stored as objects and we want to verify the presence of a specific property value.
Using any() Function with List Comprehension
any() function is an efficient way to check if a value exists in a list of objects. It stops searching as soon as it finds the first match.
Python
# Define a class to represent objects
class Item:
def __init__(self, name, price):
self.name = name
self.price = price
# Create a list of objects
items = [
Item("Laptop", 1000),
Item("Phone", 700),
Item("Tablet", 400)
]
# Check if any object has a name 'Phone'
value_to_check = "Phone"
exists = any(item.name == value_to_check for item in items)
print("Value exists:", exists)
Explanation:
- any() function iterates through the list and evaluates the condition item.name == value_to_check.
- The iteration stops as soon as a match is found, making it efficient.
- This method is concise and widely used.
Let's explore some more methods and see how we can check if value exists in Python list of objects.
Using for Loop
A for loop offers simplicity and allows customization for additional logic.
Python
# Define a class to represent objects
class Item:
def __init__(self, name, price):
self.name = name
self.price = price
# Create a list of objects
items = [
Item("Laptop", 1000),
Item("Phone", 700),
Item("Tablet", 400)
]
# Check if any object has a name 'Phone'
value_to_check = "Phone"
exists = False
for item in items:
if item.name == value_to_check:
exists = True
break
print("Value exists:", exists)
Explanation:
- This method explicitly iterates through each object in the list.
- The loop breaks immediately after finding the required value, improving efficiency.
- It is easy to understand and modify.
Using filter()
The filter() function can identify matching objects in the list.
Python
# Define a class to represent objects
class Item:
def __init__(self, name, price):
self.name = name
self.price = price
# Create a list of objects
items = [
Item("Laptop", 1000),
Item("Phone", 700),
Item("Tablet", 400)
]
# Check if any object has a name 'Phone'
value_to_check = "Phone"
exists = bool(list(filter(lambda item: item.name == value_to_check, items)))
print("Value exists:", exists)
Explanation:
- The
filter()
function filters the list based on the condition item.name == value_to_check
. - The result is converted to a list and checked for non-emptiness using
bool()
. - While useful, this method is less efficient as it processes the entire list.
Using List Comprehension
List comprehension can be used to build a list of matching objects and check if it’s non-empty.
Python
# Define a class to represent objects
class Item:
def __init__(self, name, price):
self.name = name
self.price = price
# Create a list of objects
items = [
Item("Laptop", 1000),
Item("Phone", 700),
Item("Tablet", 400)
]
# Check if any object has a name 'Phone'
value_to_check = "Phone"
exists = len([item for item in items if item.name == value_to_check]) > 0
print("Value exists:", exists)
Explanation:
- A list comprehension filters objects matching the condition.
- The length of the resulting list determines if a match exists.
- This method is less efficient as it creates a list of all matches.
Using next()
The next() function can retrieve the first matching object and indicate if a match exists.
Python
# Define a class to represent objects
class Item:
def __init__(self, name, price):
self.name = name
self.price = price
# Create a list of objects
items = [
Item("Laptop", 1000),
Item("Phone", 700),
Item("Tablet", 400)
]
# Check if any object has a name 'Phone'
value_to_check = "Phone"
exists = next((True for item in items if item.name == value_to_check), False)
print("Value exists:", exists)
Explanation:
- The generator expression inside next() checks each object for a match.
- If no match is found, the default value False is returned.
- This method is efficient as it stops after finding the first match.
Similar Reads
Python | Check if element exists in list of lists Given a list of lists, the task is to determine whether the given element exists in any sublist or not. Given below are a few methods to solve the given task. Method #1: Using any() any() method return true whenever a particular element is present in a given iterator. Python3 # Python code to demons
5 min read
Python | Check if a list exists in given list of lists Given a list of lists, the task is to check if a list exists in given list of lists. Input : lst = [[1, 1, 1, 2], [2, 3, 4], [1, 2, 3], [4, 5, 6]] list_search = [4, 5, 6] Output: True Input : lst = [[5, 6, 7], [12, 54, 9], [1, 2, 3]] list_search = [4, 12, 54] Output: False Letâs discuss certain ways
4 min read
Python | Check If A Given Object Is A List Or Not Given an object, the task is to check whether the object is a list or not. Python provides few simple methods to do this and in this article, we'll walk through the different ways to check if an object is a list:Using isinstance()isinstance() function checks if an object is an instance of a specific
2 min read
Check if Value Exists in Python Dictionary We are given a dictionary and our task is to check whether a specific value exists in it or not. For example, if we have d = {'a': 1, 'b': 2, 'c': 3} and we want to check if the value 2 exists, the output should be True. Let's explore different ways to perform this check in Python.Naive ApproachThis
2 min read
Check If Python Json Object is Empty Python users frequently work with JSON, particularly when exchanging data between multiple devices. In this article, we'll learn how to check if a JSON object is empty using Python. Check If a JSON Object Is Empty in PythonBelow, we provide examples to illustrate how to check if a JSON object is emp
3 min read