Python List Comprehensions: Write Less, Do More
Master Python list comprehensions with clear examples. Learn how to replace verbose for-loops with concise, readable one-liners that every Python developer should know.
One of the first things that makes Python feel truly powerful is list comprehensions. They let you create lists in a single, readable line instead of writing a full for-loop. Once you understand them, you’ll use list comprehensions in Python every day.
What Is a List Comprehension?
A list comprehension is a concise way to build a list from an existing iterable. The basic syntax is:
[expression for item in iterable]
Compare the two approaches:
# Traditional for-loop
squares = []
for n in range(10):
squares.append(n ** 2)
# List comprehension
squares = [n ** 2 for n in range(10)]
Both produce the same result — [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] — but the comprehension is shorter and, once you’re comfortable with the syntax, more readable.
Adding Conditions
You can filter items by adding an if clause at the end:
# Only even numbers
evens = [n for n in range(20) if n % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# Words longer than 4 characters
words = ["cat", "elephant", "dog", "hippopotamus", "ant"]
long_words = [w for w in words if len(w) > 4]
# ['elephant', 'hippopotamus']
The condition acts as a filter — only items where it evaluates to True are included.
Practical Real-World Examples
Here are three situations where list comprehensions shine:
# 1. Clean up a list of user inputs
raw = [" Alice ", "Bob ", " Charlie"]
names = [name.strip() for name in raw]
# 2. Extract values from a list of dictionaries
users = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]
ages = [user["age"] for user in users]
# 3. Convert file extensions
files = ["report.txt", "data.csv", "image.png"]
names_only = [f.split(".")[0] for f in files]
When NOT to Use Them
List comprehensions are great for simple transformations. If your logic needs multiple conditions, nested loops deeper than one level, or side effects, a regular for-loop is clearer. Readability always wins.
Conclusion
List comprehensions in Python let you write cleaner, more expressive code. Start by replacing simple for-loops that build lists — you’ll quickly develop an intuition for when they’re the right tool. Practice writing one comprehension a day and it’ll become second nature.
Read next: Python Dictionaries: The Data Structure You’ll Use Every Day
External resource: Python Docs — List Comprehensions
Related Articles
CSS Flexbox in Plain English: A Beginner's Guide
Learn CSS Flexbox with simple, visual explanations. This guide covers display flex, justify-content, align-items, flex-wrap, and practical layouts every developer needs to know.
Docker for Backend Developers: A Practical Introduction
Learn how Docker works, why backend developers need it, and how to containerize your first Python or Go application in under 30 minutes.
Environment Variables Explained: Keeping Secrets Out of Code
Learn what environment variables are and why every developer needs them. This guide covers how to use .env files, os.environ in Python, process.env in Node.js, and best practices.