Python List Comprehensions: From Loops to One-Liners
🎁 Free: AI Publishing Checklist — 7 steps in Python · Full pipeline: germy5.gumroad.com/l/xhxkzz (pay what you want, min $9.99)
You've written this a hundred times:
squares = [] for x in range ( 10 ): squares . append ( x ** 2 )
Enter fullscreen mode
Exit fullscreen mode
There's nothing wrong with it — but Python gives you a shorter, faster, and more readable way to express the same idea. By the end of this article you'll be writing that as:
squares = [ x ** 2 for x in range ( 10 )]
Enter fullscreen mode
Exit fullscreen mode
Let's build up from zero.
The Basic Syntax
The structure of a list comprehension is:
[ expression for item in iterable ]
Enter fullscreen mode
Exit fullscreen mode
Read it left to right: "give me expression , for each item in iterable ."
Before:
names = [ " alice " , " bob " , " carol " ] upper = [] for name in names : upper . append ( name .…