Lesson 8 of 26
Iterators and closures
In Python you turn a list into a new list with a comprehension. Rust uses a chain of calls for the same job. Read the chain top to bottom, like a pipeline:
xs.iter().filter(|x| **x > 0).map(|x| *x * 2).collect::<Vec<_>>()
That means "take the items, keep some, change them, build a new list". Each call is small, and the result of one call feeds the next one. Three things to know before you read the examples:
.iter()walks over aVecbut hands out references to the items, not the items themselves. That is why you see*x,&xand|&x|below. Read&as "borrowed" (lesson 13). One*gets you the value behind a reference.|x| x * 2is a closure: Python'slambda x: x * 2.- A chain is lazy, like a generator: nothing runs until something asks for a value.
.collect(),.sum()or aforloop asks for them.
You will also meet .into_iter(). It hands out the items themselves and uses up the Vec
(lesson 13). .iter() is the one you will read most.
A comprehension becomes a chain
The Python comprehension does three things in one line: loop, keep, change. In Rust each of those is a
separate call, and the type of collect is written on the left. Hover the marked lines.
numbers = [3, -1, 4, -2, 5]
doubled = [x * 2 for x in numbers if x > 0]
print(doubled)fn main() {
let numbers = vec![3, -1, 4, -2, 5];
let doubled: Vec<i32> = numbers
.iter()
.filter(|x| **x > 0)
.map(|x| *x * 2)
.collect();
println!("{:?}", doubled);
}[6, 8, 10]sum, max, min and count
Some chains end in a number instead of a list. collect is then not needed, but sum
still needs to know what kind of number to make.
scores = [7, 12, 4]
print(sum(scores), max(scores), min(scores))
print(len([s for s in scores if s > 5]))fn main() {
let scores = vec![7, 12, 4];
let total: i32 = scores.iter().sum();
let top = scores.iter().max().unwrap();
let low = scores.iter().min().unwrap();
println!("{total} {top} {low}");
let big = scores.iter().filter(|s| **s > 5).count();
println!("{big}");
}23 12 4
2enumerate and zip inside a for loop
enumerate and zip exist in Rust with the same names and the same meaning. Here the
chain ends in a for loop instead of collect, so no Vec is built.
names = ["ada", "bob"]
ages = [36, 41]
for i, (name, age) in enumerate(zip(names, ages), start=1):
print(f"{i}. {name} is {age}")fn main() {
let names = vec!["ada", "bob"];
let ages = vec![36, 41];
for (i, (name, age)) in names.iter().zip(ages.iter()).enumerate() {
println!("{}. {} is {}", i + 1, name, age);
}
}1. ada is 36
2. bob is 41Nothing runs until you ask
A chain is lazy. Building it costs nothing; the closures run when collect asks for the items.
The same is true of a Python generator. A closure with braces can hold several lines, like a function body.
def double(x):
print(f"doubling {x}")
return x * 2
chain = (double(x) for x in [1, 2, 3])
print("chain made")
print(list(chain))fn main() {
let numbers = vec![1, 2, 3];
let chain = numbers.iter().map(|x| {
println!("doubling {x}");
*x * 2
});
println!("chain made");
let values: Vec<i32> = chain.collect();
println!("{:?}", values);
}chain made
doubling 1
doubling 2
doubling 3
[2, 4, 6]any, all and rev
any and all answer a yes/no question about a whole list and stop as soon as they
know the answer. rev walks a chain backwards. Neither builds a new list.
words = ["a", "bb", "ccc"]
if any(len(w) > 2 for w in words):
print("has a long word")
if all(len(w) > 0 for w in words):
print("no empty words")
for w in reversed(words):
print(w)fn main() {
let words = vec!["a", "bb", "ccc"];
if words.iter().any(|w| w.len() > 2) {
println!("has a long word");
}
if words.iter().all(|w| !w.is_empty()) {
println!("no empty words");
}
for w in words.iter().rev() {
println!("{w}");
}
}has a long word
no empty words
ccc
bb
aWhere the Python analogy breaks
- A chain does nothing until you consume it.
xs.iter().map(...)on its own runs no code (the compiler warns you). A list comprehension runs right away; a Rust chain is more like a generator expression. .iter()hands out references. That's why closures see&x, or even&&xinsidefilter, and you write*xor**x. Python always hands you the value.collect()has to be told what to build. In Python the brackets say it:[...]or{...}. In Rust you write the type:Vec<_>,HashMap<_, _>orString.- A closure that changes a variable from outside needs that variable to be
mut, and the closure too:let mut add = |x| total += x;. Python needsnonlocalfor the same thing.
Cheat card
| Python | Rust |
|---|---|
[x * 2 for x in xs] | xs.iter().map(|x| x * 2).collect::<Vec<_>>() |
[x for x in xs if x > 0] | xs.iter().filter(|x| **x > 0).collect::<Vec<_>>() |
lambda x: x * 2 | |x| x * 2 |
def f(x):
print(x)
return x * 2 | |x| {
println!("{x}");
x * 2
} |
sum(xs) | let total: i32 = xs.iter().sum(); |
max(xs), min(xs) | xs.iter().max(), xs.iter().min() // Option, lesson 11 |
sum(1 for x in xs if x > 0) | xs.iter().filter(|x| **x > 0).count() |
for i, x in enumerate(xs): | for (i, x) in xs.iter().enumerate() { |
for x, y in zip(a, b): | for (x, y) in a.iter().zip(b.iter()) { |
any(x > 0 for x in xs) | xs.iter().any(|x| *x > 0) |
all(x > 0 for x in xs) | xs.iter().all(|x| *x > 0) |
reversed(xs) | xs.iter().rev() |