Getting the First Match From a Python List or Iterable (Overview)

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

In this video course, you’ll explore how best to approach all three scenarios.

Download

Sample Code (ZIP)

2.6 KB
Download

Course Slides (PDF)

3.4 MB

00:00 Getting the First Match From a Python List or Iterable. At some point in your Python journey, you may need to find a first item that matches a certain criterion in a Python iterable, such as a list or dictionary.

00:13 The simplest case is that you need to confirm that a particular item exists in the iterable. For example, you may want to find a name in a list of names or a substring inside a string.

00:24 In these cases, you are best off using the in operator.

00:31 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, or find a modified dictionary in a list of dictionaries based on a certain attribute. This course will cover how to best approach all three scenarios.

00:57 One option is to transform your whole interval to a new list and then use .index() to find the first item matching your criterion.

01:10 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 these situations, you are searching for a calculated property of the items you are iterating over.

01:31 In this course, you’ll learn how to match such a derived attribute without needing to do unnecessary calculations. Any code you see entered in a REPL will be using the enhanced REPL bpython.

01:44 It offers a number of enhancements over the standard REPL, including code highlighting and suggestions. So now you know what’s going to be covered, let’s get started.

Become a Member to join the conversation.