Map and Filter
Easy
+2 pts
🎯 In Python, list comprehensions handle both transforming and filtering in one readable expression:
squares = [x**2 for x in numbers]
evens = [x for x in numbers if x % 2 == 0]
lengths = [len(s) for s in words if s]
Python also has map() and filter() builtins, but list comprehensions are more idiomatic. In Rust, iterator methods like .map() and .filter() are the idiomatic approach — they replace both loops and comprehensions.
.map() — transform each element
.map() takes a closure and applies it to every element, producing a new iterator:
let doubled: Vec<i32> = vec![1, 2, 3]
.iter()
.map(|x| x * 2)
.collect();
// [2, 4, 6]
This is like [x * 2 for x in vec] …
Login to see the full exercise.
Topics