Master Python List Comprehensions: Turn Loops into One‑Liners
This tutorial explains Python list comprehensions, showing how to replace traditional for‑loops with concise one‑line expressions for generating simple, filtered, nested, and transformed lists, complete with clear code examples and step‑by‑step explanations.
Preface
Teaching others is the best way to learn a language. This article starts from basic Python tutorials and gradually advances. Readers with solid Python fundamentals are encouraged to explore advanced projects like web scraping.
Syntax Features
List comprehensions are a powerful, concise syntax for creating lists.
Simple List
Generate a simple list using range() and convert it to a list with list(): print(list(range(1, 11))) To create an arithmetic sequence from 1 to 50 with a step of 5, add the step argument to range():
print(list(range(1, 51, 5)))Complex List
Generate squares of numbers 1 through 5 using a regular loop:
L = []
for i in range(1, 6):
L.append(i*i)
print(L)The same result can be achieved with a single list comprehension:
print([x*x for x in range(1, 6)])Filtering Data
Add an if clause to filter data, e.g., squares of odd numbers from 1 to 5:
print([x*x for x in range(1, 6) if x % 2 == 1])Nested For Loops
Use double for‑loops inside a comprehension to combine characters from two strings:
print([m+n for m in 'bruce' for n in 'pk'])Processing Existing Data
Transform existing lists, such as converting all strings to uppercase:
L = ['hello', 'bruce', 'pk']
print([i.upper() for i in L])Extract keys and values from a dictionary using a comprehension:
d = {'B': '百度', 'A': '阿里', 'T': '腾讯'}
print([k + '=' + v for k, v in d.items()])Conclusion
Try the code examples yourself; they are simple and effective. Your feedback and support are appreciated.
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.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
