Lesson 27 of 34
List Comprehensions: Lists in One Line
8 min 30 XP
Building a list with a loop can be written in one line: [expression for item in collection]. It's one of Python's most loved features.
Example: edit me and press Run
Output Loading Python (first time takes a few seconds)
Press Run to see the result here.Add an if at the end to keep only the items that match (a filter).
Example: edit me and press Run
Output Loading Python (first time takes a few seconds)
Press Run to see the result here.Use { } for a dictionary comprehension. If a comprehension gets very long, a normal loop is easier to read.