Getting the First Matching Item in a Python List

00:00 How to Get the First Matching Item in a Python List. You may already know about the in Python operator, which can tell you if an item is in an iterable.

00:11 While this is the most efficient method that you can use for this purpose, sometimes you may need to match based on a calculated property of the items, such as their lengths. For example, you might be working with a list of dictionaries, typical of what you might get when processing JSON data.

00:30 On-screen, you’ll see some country data from the country-json repository being saved as a dictionary in a Python file. This will allow the data to be imported quickly across multiple REPL sessions, saving you time if you tackle this course across multiple sittings.

01:25 You might want to grab the first dictionary that has a population of over one hundred million. The in operator isn’t a great choice for two reasons.

01:33 First, you’d need to have the full dictionary to match it, and secondly, it wouldn’t return the actual object, but a Boolean value.

01:58 There’s no way to use in if you need to find a dictionary based on an attribute of it, such as population. The most readable way to find and manipulate the first element in the list based on a calculated value is to use the humble for loop.

02:25 Instead of printing the target object, you can do anything you like with it in the for loop body. After you are done, be sure to break the for loop so that you don’t needlessly search the rest of the list.

02:37 Note that using the break statement applies if you’re looking for the first match from the iterable. If you’re looking to get or process all of the matches, then you can do without the break.

02:50 The for loop approach is the one taken by the first package, which is a tiny package you can download from PyPI that exposes a general-purpose function, first().

03:02 This function returns the first truthy value from an iterable by default, with an optional key parameter to return the first truthy value after it’s been passed through the key argument.

03:16 Note that on Python 3.10 and later, you can use structural pattern matching to match these kinds of data structures in a way that you may prefer. On-screen, you’ll see how you can use this technique to match a country with a population of more than a hundred million.

03:43 Here you use a guard to only match certain populations.

03:52 Using structural pattern matching instead of regular conditional statements can be more readable and concise if the matching patterns are complex enough.

04:04 Later in the course, you’ll implement your own variation of the first() function, but next, you’ll look into another way of returning a first match: using generators.

Become a Member to join the conversation.