A list comprehension in Python is a concise way to create lists by transforming elements from an existing iterable (like a list, range, or string) through a single line of code. It makes a new list by applying an expression to each item in the iterable, optionally filtering out items with a condition.
Basic Syntax
- Expression: what you want to do for each item, like modify
- Item: each element from the iterable
- Iterable: the collection you’re looping through
- Condition: optional, a filter that determines which items are included
Examples
When practicing Higher Order Functions, I discovered list comprehensions when trying to build my custom_map()
function in line 4: