![]() |
In Python, checking if a specific value exists in a list of objects is a common task. There are several methods to achieve this, and in this article, we will explore five generally used methods with simple code examples. Each method provides a different approach to checking for the existence of a value in a list of objects. To Check If Value Exists in Python List Of ObjectsBelow, are the ways To Check If Value Exists In Python List Of Objects in Python.
Create a List of ObjectsIn this example, the below code defines a `Person` class with attributes for name and age. An array `people` is then created, containing instances of the `Person` class, and the type of the `people` array is printed, resulting in “<class ‘list’>”. Python3
Output
<class 'list'> Check If Value Exists In Python Using a For LoopIn this example, below code iterates through the list of people and checks if there is a person with age 30. If found, it prints “A person with age 30 exists in the list,” otherwise, it prints “No person with age 30 found in the list.” Python3
Output A person with age 30 exists in the list.
Check If Value Exists In Python Using
|
# Using the filter function to check for the existence of a person with age 30 target_age = 30 filtered_people = filter ( lambda person: person.age = = target_age, people) found = any (filtered_people) if found: print (f "A person with age {target_age} exists in the list." ) else : print (f "No person with age {target_age} found in the list." ) |
Output
A person with age 30 exists in the list.
lambda
() FunctionIn this example, below code utilizes the `map` function with a lambda expression to create an iterable of boolean values indicating whether each person’s age is 30. The `any` function then checks if at least one of these values is True, and it prints either “A person with age 30 exists in the list.”
# Using the map and any functions to check for the existence of a person with age 30 target_age = 30 found = any ( map ( lambda person: person.age = = target_age, people)) if found: print (f "A person with age {target_age} exists in the list." ) else : print (f "No person with age {target_age} found in the list." ) |
Output
A person with age 30 exists in the list.
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |