Julia Iterating Collections
Iterating a collection means visiting each of its items one at a time, usually inside a for loop. The loop body runs once for every item.
Loop over pairs in key order
Sorting the pairs first visits them in key order. Each round splits one pair into its key and value.
d = Dict("b" => 2, "a" => 1)
for (k, v) in sort(collect(d))
println(k, " => ", v)
endeachindex gives the positions
eachindex gives each position of the array in turn. The loop prints every position next to its item.
a = [10, 20, 30]
for i in eachindex(a)
println(i, ": ", a[i])
endLoop over the characters of a string
A string is a collection of characters. The loop below prints one character per line.
for c in "Ana"
println(c)
endExample
ages = Dict("Ben" => 25, "Ana" => 31)
for (k, v) in sort(collect(ages))
println(k, " is ", v)
end
word = "hi"
for c in word
println(c)
endKey points
- Pair loop: for (k, v) in d runs the loop once per pair, with k as the key and v as the value.
- Sorted pairs: sort(collect(d)) visits a dictionary's pairs in key order.
- Pair print: a pair prints in the form "a" => 1.
- eachindex: eachindex(a) gives the indexes of an array, from 1 to its length.
- String loop: a for loop over a string visits its characters one at a time.
In this example, the dictionary pairs are visited in key order, so Ana's line prints before Ben's. The second loop then visits the characters of "hi" one at a time, printing h and then i.
Note
sorting the pairs first makes dictionary output the same on every run.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
Why does the dictionary loop use sort(collect(d)) instead of d alone?