How to do a FirstOrDefault in Python

Are you looking for a way to get an item from a list based on a predicate or return None if the predicate is not satisfied? C# has the FirstOrDefault function from LINQ to achieve this. How can you do it in Python? After reading this, you have learned how to create a list of objects and finding elements in that list.

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

Filter list

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.

FirstOrDefault

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

Complete example

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

Conclusion

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.

Written by Loek van den Ouweland on October 06, 2018. Questions regarding this artice? You can send them to the address below.
By using this site, you acknowledge that you have read and understand our Cookie and Privacy Policy.