In Python, list comprehension is a method of manipulating lists in a compact/concise way. Comprehensions use the same keywords as loop and conditional blocks, and aim to focus on the actual data rather than on the procedure — which gives us different ways of thinking about our logic.
The general syntax of list comprehension is:
new_list = [expr for item in iterable if condition]Other data types, like sets or dictionaries, also have corresponding comprehensions. That said, past a simple level they stop being useful clarifying tools and we should then just use functions.
This is equivalent to the functional programming construct where we iterate, filter, map, and collect:
let new_list: Vec<u32> = vec
.iter()
.filter(|elem| condition(elem))
.map(|elem| expr(elem)))
.collect()Example
To iterate through a list and find even numbers:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = []
for number in numbers:
if number % 2 == 0:
even_numbers.append(number)With list comprehension:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [number for number in numbers if number % 2 == 0]