Master Python List Comprehensions: 3 Techniques, Examples, and Exercises
This tutorial explains Python list comprehensions, shows three practical methods with code examples and images, covers filtering and multi‑variable comprehensions, provides an exercise with a solution, and summarizes key takeaways for writing concise, readable code.
1. Introduction
List comprehensions are a built‑in, simple yet powerful way to create lists in Python.
2. Case Study
Three Methods
To generate the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] you can use list(range(1, 11)):
print(list(range(1, 11)))How to generate [1×1, 2×2, …, 10×10]?
1. Method One – Loop
L = []
for x in range(1, 11):
L.append(x * x)
print(L)Loops are verbose; a list comprehension can replace the loop in one line:
print([x * x for x in range(1, 11)])In a list comprehension the expression appears first, followed by the for clause.
You can also add an if clause to filter, e.g., squares of even numbers:
print([x * x for x in range(1, 11) if x % 2 == 0])2. Two‑level loop – Cartesian product
L = []
for x in range(1, 11):
L.append(x * x)
print([m + n for m in 'ABC' for n in 'XYZ'])Three‑level (or deeper) loops are rarely needed.
3. Concise code with list comprehensions
Example: list all files and directories in the current folder:
import os
print([d for d in os.listdir('.')])For dictionaries you can iterate over key and value simultaneously:
d = {'x': 'A', 'y': 'B', 'z': 'C'}
for k, v in d.items():
print(k, '=', v)Using two variables in a comprehension:
print([k + '=' + v for k, v in d.items()])Convert all strings in a list to lowercase:
L = ['Hello', 'World', 'IBM', 'Apple']
print([s.lower() for s in L])If the list contains non‑string items, calling lower() raises an error. Use isinstance to filter strings:
L = ['Hello', 'World', 18, 'Apple', None]
print([s.lower() for s in L])x = 'abc'
y = 123
print(isinstance(x, str))
print(isinstance(y, str))3. Exercise
Modify the list comprehension to include an if clause so that only string elements are converted to lowercase.
# -*- coding: utf-8 -*-
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = ???
# Expected output: ['hello', 'world', 'apple']
print(L2)Reference solution:
L2 = [s.lower() for s in L1 if isinstance(s, str)]4. Conclusion
This article introduced Python list comprehensions, demonstrated three approaches, discussed common pitfalls, and provided an exercise to deepen understanding.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
