In programming, it is very common that we need to get the first item from a list that matches some criteria. Let's look at our options in Python and if we can do it without a for loop.
Say we have defined class Fruit:
@dataclass(frozen=True) class Fruit: name: str color: strAnd we have a list of fruits like this:
fruits = [ Fruit('apple', 'red'), Fruit('orange', 'orange'), Fruit('lemon', 'yellow'), Fruit('lime', 'green'), Fruit('banana', 'yellow'), Fruit('plum', 'blue'), ]We want to get the first fruit from the list with a yellow colour.
Using a for loopPermalink
The simplest way to do this is to iterate through the items in the list, check the colour, and if it's yellow, return the item.
def get_first_yellow(list_of_fruits): for f in list_of_fruits: if f.color == 'yellow': return f return None get_yellow(fruits) # will return # Fruit(name='lemon', color='yellow')This code is very efficient as we terminate the loop (and the function) on the the first match, so we don't do any unnecessary work.
If there is no yellow fruit loop, we return None.
Can we do this without a loop?Permalink
We can avoid the loop by using list comprehension.
def get_first_yellow_no_loop(list_of_fruits): matches = [f for f in list_of_fruits if f.color == 'yellow'] if matches: return matches[0] return NoneWhile this also works, have we gained anything?
The code is not shorter.
It is not clearer.
And, it's also less efficient because: - it will go through the whole list (not only until it finds the first match) - create a new list of matching items - do if and only then return
Loop was better.
Can we do this without the loop with the same efficiency?
Generator expression and the next() functionPermalink
We could use a generator expression to avoid iterating through the whole list.
The generator doesn't create a new list. It outputs values on the fly when we need them.
We can rewrite our function with a generator expression like this.
def get_first_yellow_generator(list_of_fruits): matches = (f for f in list_of_fruits if f.color == 'yellow') return next(matches, None)First, we created a generator with generator expression and assigned it to variable matches.
Then, we used the built-in function next(), which retrieves the next item from our matches generator.
The second parameter to the next() is the value to return if there is no next item. If we don't provide this value, then the next() would throw a StopIteration exception if there are no yellow items in our list.
This code is very efficient because it doesn't iterate the whole list or allocate any memory for a new list.
It's also clear what's going on to any experienced Python developer. We can also make it one line if you're into one-liners.
def get_first_yellow_one_line(list_of_fruits): return next((f for f in list_of_fruits if f.color == 'yellow'), None)SummaryPermalink
There are multiple ways to get the first matching item from a list (or any iterable).
There is nothing wrong with a for loop here. We're not mutating any variables, and it's very efficient.
As we can see, replacing the for loop with a comprehension doesn't help us at all, so I don't recommend that (unless we use the filtered list for some further processing).
We can avoid the for loop and keep clarity and efficiency by using generator expression.
This code will be shorter and might be preferred by more experienced Python developers but will be a bit harder to understand for people just starting with Python.
You might also like
Join the newsletter
Subscribe to get new articles about Python, code and programming into your inbox!
Python list is an actual container as it stores elements of all the data types as a collection. Knowledge of certain list operations is necessary for day-day programming.
To find an element in the Python list, use the list index() method. The list index() is a built-in method that searches for an element in the list and returns its index. There is another approach which is a Python Linear search on the list.
Find an element using the list index() method
To find an element in the list, use the Python list index() method, The index() is an inbuilt Python method that searches for an item in the list and returns its index. The index() method finds the given element in the list and returns its position.
If the same element is present more than once, the method returns the index of the first occurrence of the element. The index in Python starts from 0, not 1. So, through an index, we can find the position of an element in the list.
See the following code example.
# app.py streaming = ['netflix', 'hulu', 'disney+', 'appletv+'] index = streaming.index('disney+') print('The index of disney+ is:', index)Output
➜ pyt python3 app.py The index of disney+ is: 2 ➜ pytThe index() method takes a single argument, which is the element and returns its position in the list.
Python search on the list
It is the straightforward approach is to do a linear search; for example,
- Start from the leftmost item of the list, and one by one, compare x with each item of the list.
- If x matches with an item, return True.
- If x doesn’t match with any of the items, return False.
See the following code.
# app.py def search(list, platform): for i in range(len(list)): if list[i] == platform: return True return False streaming = ['netflix', 'hulu', 'disney+', 'appletv+'] platform = 'netflix' if search(streaming, platform): print("Platform is found") else: print("Platform does not found")We have first created a user-defined function called a search that accepts two arguments in the above code.
The first argument is our list in which we need to find the item, and the second parameter is the platform, which is the string we need to search in the list.
So, we are looping through a list and comparing each list element to the platform argument.
If both are matched, the element is found; otherwise, it is not.
Output
➜ pyt python3 app.py Platform is found ➜ pytCheck if the item exists in the list using the “in” operator
To check if an element exists in the list, use Python in operator.
Syntax
element in listIt will return True if an element exists in the list; else, it will return False.
See the following code.
# app.py streaming = ['netflix', 'hulu', 'disney+', 'appletv+'] platform = 'hulu' if platform in streaming: print('Hulu is in the streaming service business') else: print('It does not include')Output
➜ pyt python3 app.py Hulu is in the streaming service business ➜ pytFiltering a collection in Python
To find all elements in a sequence that meet a specific condition, use the list comprehension or generator expressions.
See the following code example.
# app.py streaming = ['netflix', 'hulu', 'disney+', 'appletv+'] platform = 'hulu' result = any(len(elem) == 8 for elem in streaming) if result: print("Yes, string with length 8 is found") else: print('Not found')In the above code, we search for an element whose string length is 8. If found, it will print “Yes, string with length 8 is found”; otherwise, not found.
Output
➜ pyt python3 app.py Yes, string with length 8 is found ➜ pytConclusion
Python lists can contain different data types like integer, string, boolean, etc. Sometimes, it requires to search particular elements in the list. The items can be searched in the python list in various ways. We have seen the ways like search elements in the list by index, linear search on the list,
That is it for the Python find in list example.
Related Posts
How to Access Characters in String by Index in Python
How to Convert Python List to JSON
How to Convert Python Dictionary to String
How to Convert Python List to Dictionary
How to Convert Python String to List and List to String