Finding the First Match From a Python Iterable

Real Python · Beginner ·🌐 Frontend Engineering ·3y ago

Key Takeaways

This video demonstrates how to find the first match from a Python iterable using various methods, including the in operator, for loops, the first package, and generators.

Full Transcript

getting the first match from our python list all 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 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 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 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 one option is to transform your whole iterable to a new list and then use index to find the first item matching your Criterion 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're searching for a calculated property of the items you're iterating over 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 raffle will be using the enhanced raffle B python it offers a number of enhancements over the standard raffle including code highlighting and suggestions so now you know what's going to be covered let's get started 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 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 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 raffle sessions saving you time if you tackle this course across multiple settings you might want to grab the first dictionary that has a population of over 100 million the in operator isn't a great choice for two reasons 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 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 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 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 the for Loop approach is the one taken by the first package which is a tiny package you can download from Pi Pi 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 truthy value after it's been passed through the key argument 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 100 million here you use a guard to only match certain populations using structural pattern matching instead of regular conditional statements can be more readable and concise if the matching patterns are complex enough 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 using python generators to get the first match python generator iterators are memory efficient iterables that can be used to find the first element in a list or any iterable they're a core feature of python being used extensively under the hood it's likely you've already used generators without even knowing it the potential issue with generators is that they're a bit more abstract and as such not quite as readable as for loops you do get some performance benefits from generators but these are often negligible when the importance of readability is taken into consideration that said using them can be fun and level up your python game in Python you can make a generator in various ways but in this course you'll be working with generator comprehensions once you've defined a generator iterator you can then call the next function with the generator as an argument producing the countries one by one until the country's list is exhausted to find the first element matching a certain criteria in a list you can add a conditional expression to the generator comprehension so the resulting iterator will only yield items that match the criteria in the example seen on screen you use a conditional expression to generate items based on whether the population attribute is over 100 million so now the generator will only produce dictionaries with a population attribute of over 100 million this means that the first time you call next with the generator iterator it will yield the first element that you're looking for in the list just like the for Loop version note that you'll get an exception if you call next and there's no match or the generator is exhausted to prevent this you can pass in a default argument to next monster generator is finished producing matches it will return the default value that's been passed in since you're returning none you get no output in the rebel if you hadn't passed in the default value you would get a stop iteration exception in terms of readability a generator isn't quite as natural as a for Loop so why would you use one for this purpose well in the next section of the course you'll be doing a quick performance comparison to find out

Original Description

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. This is a portion of the complete course, which you can find here: https://realpython.com/courses/python-first-match/ The rest of the course covers: - Finding and modifying a dictionary in a list of dictionaries based on a certain attribute - Comparing the Performance Between Loops and Generators - Graphing Performance With matplotlib - Making a Reusable Python Function to Find the First Match
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Real Python · Real Python · 0 of 60

← Previous Next →
1 A better Python REPL – bpython vs python interpreter
A better Python REPL – bpython vs python interpreter
Real Python
2 Introducing large-type.com – A Utility Website
Introducing large-type.com – A Utility Website
Real Python
3 Reading Hacker News Without Wasting Tons of Time
Reading Hacker News Without Wasting Tons of Time
Real Python
4 Forward References and Python 3 Type Hints
Forward References and Python 3 Type Hints
Real Python
5 Using Sublime Text as your Git Editor
Using Sublime Text as your Git Editor
Real Python
6 Python Code Linting and Auto-Complete for Sublime Text
Python Code Linting and Auto-Complete for Sublime Text
Real Python
7 Make your Python Code More Readable with Custom Exceptions
Make your Python Code More Readable with Custom Exceptions
Real Python
8 Write Better Tests with Sublime Text's Split Layout Feature
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
9 How to Use Sublime Text from the Command Line
How to Use Sublime Text from the Command Line
Real Python
10 Rename Variables with Multiple Selection in Sublime Text
Rename Variables with Multiple Selection in Sublime Text
Real Python
11 Sublime Text Settings for Writing PEP 8 Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
12 Write Cleaner Python with Sublime Text's Indent Guides
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
13 Sublime Text Whitespace Settings for Python Development
Sublime Text Whitespace Settings for Python Development
Real Python
14 Function Argument Unpacking in Python
Function Argument Unpacking in Python
Real Python
15 Python Code Review: Debugging and Refactoring "Conway's Game of Life" +  Automated Tests
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
16 Using "get()" to Return a Default Value from a Python Dict
Using "get()" to Return a Default Value from a Python Dict
Real Python
17 A Python Shorthand for Swapping Two Variables
A Python Shorthand for Swapping Two Variables
Real Python
18 Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
19 Click & Jump to Test Failures from the Command Line (iTerm2)
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
20 Setting up Sublime Text for Python Developers
Setting up Sublime Text for Python Developers
Real Python
21 Sublime Text + Python Guide Overview
Sublime Text + Python Guide Overview
Real Python
22 Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
23 Type-Checking Python Programs With Type Hints and mypy
Type-Checking Python Programs With Type Hints and mypy
Real Python
24 A Shorthand for Merging Dictionaries in Python 3.5+
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
25 Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
26 My Python Code Looks Ugly and Confusing – Help!
My Python Code Looks Ugly and Confusing – Help!
Real Python
27 Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
28 Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
29 Programmer Portfolio – Example and Walkthrough
Programmer Portfolio – Example and Walkthrough
Real Python
30 How to Get Your 1st Speaking Gig at a Tech Conference
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
31 How to Build Your Public Speaking Skills as a Developer
How to Build Your Public Speaking Skills as a Developer
Real Python
32 The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
33 Setting up Sublime Text for Python Developers – Lesson #1
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
34 Cool New Features in Python 3.6
Cool New Features in Python 3.6
Real Python
35 "is" vs "==" in Python – What's the Difference? (And When to Use Each)
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
36 Emulating switch/case Statements in Python with Dictionaries
Emulating switch/case Statements in Python with Dictionaries
Real Python
37 Python Function Argument Unpacking Tutorial (* and ** Operators)
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
38 What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
39 A Crazy Python Dictionary Expression ?!
A Crazy Python Dictionary Expression ?!
Real Python
40 String Conversion in Python: When to Use __repr__ vs __str__
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
41 Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
42 Optional Arguments in Python With *args and **kwargs
Optional Arguments in Python With *args and **kwargs
Real Python
43 Python Context Managers and the "with" Statement (__enter__ & __exit__)
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
44 Installing Python Packages with pip and virtualenv / venv
Installing Python Packages with pip and virtualenv / venv
Real Python
45 "For Each" Loops in Python with enumerate() and range()
"For Each" Loops in Python with enumerate() and range()
Real Python
46 Python Code Review: LibreOffice Automation and the Python Standard Library
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
47 Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
48 Python Tutorial: List Comprehensions Step-By-Step
Python Tutorial: List Comprehensions Step-By-Step
Real Python
49 Leveraging Python's Implicit "return None" Statements
Leveraging Python's Implicit "return None" Statements
Real Python
50 What's the meaning of underscores (_ & __) in Python variable names?
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
51 Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
52 Writing automated tests for Python command-line apps and scripts
Writing automated tests for Python command-line apps and scripts
Real Python
53 How to find great Python packages on PyPI, the Python Package Repository
How to find great Python packages on PyPI, the Python Package Repository
Real Python
54 Immutable vs Mutable Objects in Python
Immutable vs Mutable Objects in Python
Real Python
55 PyPI vs Warehouse, the Next-Generation Python Package Repository
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
56 pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
57 My Experience at PyCon 2017 in Portland
My Experience at PyCon 2017 in Portland
Real Python
58 Pylint Tutorial – How to Write Clean Python
Pylint Tutorial – How to Write Clean Python
Real Python
59 "Reverse a List in Python" Tutorial: Three Methods & How-to Demos
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
60 Python Refactoring: "while True" Infinite Loops & The "input" Function
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python

This video teaches how to find the first match in a Python iterable using various methods, including the in operator, for loops, and generators. It covers the importance of readability and performance in coding.

Key Takeaways
  1. Use the in operator to check for existence in an iterable
  2. Implement a for loop to find the first match
  3. Use the first package to find the first truthy value
  4. Create a generator comprehension to find the first match
  5. Use the next function to retrieve the first match from a generator
💡 Generators can be used for memory efficiency, but may compromise readability.

Related Reads

Up next
How to Speed Up Your WordPress Website with WP Rocket ⚡Tutorial 2026
Matt Tutorials
Watch →