Getting the First Match From a Python List or Iterable (Summary)
In this video course, you’ve learned how to find the first element in a list or any iterable in a variety of ways. You learned that the fastest and most basic way to match is by using the in
operator, but you’ve seen that it’s limited for anything more complex. So you’ve examined the humble for
loop, which will be the most readable and straightforward way. However, you’ve also looked at generators for that extra bit of performance and swagger.
Finally, you’ve looked at one possible implementation of a function that gets the first item from an iterable, whether that be the first truthy value or a value transformed by a function that matches on certain criteria.
Further Investigation:
- Python Generators 101
- Understanding Python List Comprehensions
- Prettify Your Data Structures With Pretty Print in Python
- Python Timer Functions: Three Ways to Monitor Your Code
- Python Plotting With Matplotlib (Guide)
- Structural Pattern Matching
first
: The function you always missed in Python- For Loops in Python (Definite Iteration)
Congratulations, you made it to the end of the course! What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment in the discussion section and let us know.
00:00
Summary. Well done, you’ve made it to the end of the course. In it, you’ve learned how to find the first element in an iterable in a variety of ways. You learned that the fastest and most basic way to match is using the in
operator, but you’ve seen that it’s limited for anything more complex.
00:18
You examined the humble for
loop, which will be the most readable and straightforward way. You also looked at generators for that extra bit of performance. Finally, you looked at a possible implementation of a function that gets the first item from an iterable, whether that’s the first truthy value or a value transformed by a function that matches on certain criteria. With this knowledge, you should be better equipped to deal with this in real-world situations and more aware of the performance of different solutions for the same problem.
00:50 We hope you found this course useful, and we’ll see you again soon at realpython.com.
Become a Member to join the conversation.