Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22875

Real Python: How to Get the First Match From a Python List or Iterable

$
0
0

At some point in your Python journey, you may need to find the first item that matches a certain criterion in a Python iterable, such as a list or dictionary.

The simplest case is that you need to confirm that a particular item exists in the iterable. For example, you want to find a name in a list of names or a substring inside a string. In these cases, you’re best off using the in operator. However, there are many use cases when you may want to look for items with specific properties. For instance, you may need to:

  • Find a non-zero value in a list of numbers
  • Find a name of a particular length in a list of strings
  • Find and modify a dictionary in a list of dictionaries based on a certain attribute

This tutorial will cover how best to approach all three scenarios. One option is to transform your whole iterable to a new list and then use .index() to find the first item matching your criterion:

>>>
>>> names=["Linda","Tiffany","Florina","Jovann"]>>> length_of_names=[len(name)fornameinnames]>>> idx=length_of_names.index(7)>>> names[idx]'Tiffany'

Here, you’ve used .index() to find that "Tiffany" is the first name in your list with seven characters. This solution isn’t great, partly because you calculate the criterion for all elements, even if the first item is a match.

In the above situations, you’re searching for a calculated property of the items you’re iterating over. In this tutorial, you’ll learn how to match such a derived attribute without needing to do unnecessary calculations.

Sample Code:Click here to download the free source code that you’ll use to find the first match in a Python list or iterable.

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. 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, like their lengths.

For example, you might be working with a list of dictionaries, typical of what you might get when processing JSON data. Check out this data that was obtained from country-json:

>>>
>>> countries=[... {"country":"Austria","population":8_840_521},... {"country":"Canada","population":37_057_765},... {"country":"Cuba","population":11_338_138},... {"country":"Dominican Republic","population":10_627_165},... {"country":"Germany","population":82_905_782},... {"country":"Norway","population":5_311_916},... {"country":"Philippines","population":106_651_922},... {"country":"Poland","population":37_974_750},... {"country":"Scotland","population":5_424_800},... {"country":"United States","population":326_687_501},... ]

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. One, you’d need to have the full dictionary to match it, and two, it wouldn’t return the actual object but a Boolean value:

>>>
>>> target_country={"country":"Philippines","population":106_651_922}>>> target_countryincountriesTrue

There’s no way to use in if you need to find the dictionary based on an attribute of the dictionary, 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 a humble for loop:

>>>
>>> forcountryincountries:... ifcountry["population"]>100_000_000:... print(country)... break...{"country": "Philippines", "population": 106651922}

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

Note: 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 break.

The for loop approach is the one taken by the first package, which is a tiny package that you can download from PyPI that exposes a general-purpose function, first(). This function returns the first truthy value from an iterable by default, with an optional key parameter to return the first value truthy value after it’s been passed through the key argument.

Read the full article at https://realpython.com/python-first-match/ »


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]


Viewing all articles
Browse latest Browse all 22875

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>