Making a Reusable Python Function to Find the First Match
00:00 Making a Reusable Python Function to Find the First Match. Let’s say the iterables that you expect to use are going to be on the large side, and you are interested in squeezing every bit of performance out of your code.
For that reason, you’ll use generators instead of a
for loop. You’ll also be dealing with a variety of different iterables with a variety of items and want flexibility in the way that you match, so you’ll design your function to be able to accomplish the following goals: returning the first truthy value, returning the first match, returning the first truthy result of values being passed through a key function, returning the first match of values being passed through a key function, and returning a default value if there’s no match.
00:51 While there are many ways to implement this, here’s a way to do it with pattern matching, which is available in Python 3.10 and later. You can call the function with up to four arguments, and it will behave differently depending on the combination of arguments that you pass into it.
The function’s behavior mainly depends on the
key arguments. That’s why the
match statement checks if
value is None and uses the
callable() function to learn whether
key is a function. For example, if both the
match conditions are
True, then it means that you’ve passed in a key but no value.
That’s a direct match with the value provided. Once
match is over, you have your generator. All that’s left to do is to call
next() with the generator and the
default argument for the first match.
With this function, you can search for matches in four different ways. You can get the first truthy item, the first item matching the
value argument, the first result of
key(item) that equals the
You can still accomplish the same effect as seen earlier by relying on the
key parameter. As with
matplotlib, the command to install
first into your virtual environment is the same regardless to the platform you are working on.
05:50 Regardless of which implementation you ultimately use, you now have a performant, reusable function that can get the first item you need. In the next section of the course, you’ll take a look back at what you’ve learned.
Become a Member to join the conversation.