This tutorial will teach you how to write one-line for loops in Python using the popular expert feature of list comprehension. After you’ve learned the basics of list comprehension, you’ll learn how to restrict list comprehensions so that you can write custom filters quickly and effectively.
Are you ready? Let’s roll up your sleeves and learn about list comprehension in Python!
List Comprehension Basics
The following section is based on my detailed article List Comprehension [Ultimate Guide]. Read the shorter version here or the longer version on the website—you decide!
This overview graphic shows how to use list comprehension statement to create Python lists programmatically:
List comprehension is a compact way of creating lists. The simple formula is
[expression + context].
- Expression: What to do with each list element?
- Context: What elements to select? The context consists of an arbitrary number of
[x for x in range(3)] creates the list
[0, 1, 2].
Have a look at the following interactive code snippet—can you figure out what’s printed to the shell? Go ahead and click “Run” to see what happens in the code:
Exercise: Run the code snippet and compare your guessed result with the actual one. Were you correct?
Now, that you know about the basics of list comprehension (expression + context!), let’s dive into a more advanced example where list comprehension is used for filtering by adding an if clause to the context part.
List Comprehension for Filtering (using If Clauses)
You can also modify the list comprehension statement by restricting the context with another if statement:
Problem: Say, we want to create a list of squared numbers—but you only consider even and ignore odd numbers.
Example: The multi-liner way would be the following.
squares =  for i in range(10): if i%2==0: squares.append(i**2) print(squares) # [0, 4, 16, 36, 64]
You create an empty list
squares and successively add another square number starting from 0**2 and ending in 8**2—but only considering the even numbers 0, 2, 4, 6, 8. Thus, the result is the list
[0, 4, 16, 36, 64].
Again, you can use list comprehension
[i**2 for i in range(10) if i%2==0] with a restrictive if clause (in bold) in the context part to compress this in a single line of Python code:
print([i**2 for i in range(10) if i%2==0]) # [0, 4, 16, 36, 64]
This line accomplishes the same output with much less bits.
Related Article: Python One Line For Loop
Python One-Liners Book: Master the Single Line First!
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.
Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.
You’ll also learn how to:
- Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
- Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
- Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
- Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
- Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.