When you call FirstOrDefault
on a list of objects in C#, the function returns an item or null
. This example will do the same in Python by combining list comprehension to filter the list and the next function to iterate over the result and return an object or None
.
Start by creating an Employee
class and a list of its instances like this:
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
employees = [
Employee("Vera", 35000),
Employee("Chuck", 24000),
Employee("Dave", 37500)
]
for e in employees:
print(e.name)
Which outputs:
Vera
Chuck
Dave
Filtering the list with list comprehension looks like this:
print([e.name for e in employees if e.name == "Chuck"])
Output:
['Chuck']
As you see, the result is a list.
To get an object or None, we use the next
function:
chuck = next((e for e in employees if e.name == "Chuck"), None)
print(chuck.name)
Notice how the ([...])
has been replaced with ((...))
. The result of the list comprehension is now a generator object that is iterable by the next function
Output:
Chuck
Here is the full code and some more examples.
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
employees = [
Employee("Vera", 35000),
Employee("Chuck", 24000),
Employee("Dave", 37500)
]
chuck = next((e for e in employees if e.name == "Chuck"), None)
print(chuck.name)
first_salary_over_30000 = next((e for e in employees if e.salary > 30000), None)
print(first_salary_over_30000.name)
# No item in list. Return None
first_salary_over_40000 = next((e for e in employees if e.salary > 40000), None)
print(first_salary_over_40000)
Technically this is FirstOrNone
functionality but you can replace None
with any other value.
Output:
Chuck
Vera
None
Although FirstOrDefault
is not an out-of-the-box function in Python, you’ve learned how easy it is to get the functionality you are looking for.
Also check out my article on how to use the Javascript Find Function to do the same in Javascript.