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
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 tips and tricks, regular expressions, machine learning, core data science topics, and 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!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become 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.
Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.