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