Skip to content
AgileLogics
6 min read

Working with Arrays

Prerequisites: Arrays

Julia has a large set of built-in functions for arrays:

xs = [4, 8, 15, 16, 23, 42]
println(sum(xs), " ", prod([1, 2, 3, 4]), " ", maximum(xs), " ", minimum(xs))
println(sum(xs) / length(xs))
println(extrema(xs))
println(argmax(xs), " ", findfirst(x -> x > 10, xs))
println(findall(iseven, xs))
println(count(isodd, xs))
println(reverse(xs))
println(sort(xs, rev=true))
println(unique([1, 2, 2, 3, 1]))
println(vcat([1, 2], [3, 4]))
108 24 42 4
18.0
(4, 42)
6 3
[1, 2, 4, 6]
2
[42, 23, 16, 15, 8, 4]
[42, 23, 16, 15, 8, 4]
[1, 2, 3]
[1, 2, 3, 4]
  • argmax returns the index of the largest element.
  • findfirst(predicate, xs) returns the first index where the predicate is true; findall returns all of them.
  • x -> x > 10 is an anonymous function — a small function without a name (covered in the functions lessons).
  • vcat concatenates vertically; append!(a, b) appends in place.

Comprehensions

A comprehension builds an array from a loop in one line:

squares = [n^2 for n in 1:6]
println(squares)
evens = [n for n in 1:20 if n % 6 == 0]
println(evens)
pairs = [(i, j) for i in 1:2 for j in 1:3]
println(pairs)
println(sum(n^2 for n in 1:100))
[1, 4, 9, 16, 25, 36]
[6, 12, 18]
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)]
338350

Without the brackets, n^2 for n in 1:100 is a generator: it makes values one at a time instead of building an array first, which saves memory inside functions like sum.

map and filter

names = ["ada", "grace", "alan"]
println(map(uppercase, names))
println(map(length, names))
println(filter(n -> startswith(n, "a"), names))
println(map(x -> x * 2, [1, 2, 3]))
["ADA", "GRACE", "ALAN"]
[3, 5, 4]
["ada", "alan"]
[2, 4, 6]

map(f, xs) applies f to every element; filter(f, xs) keeps the elements for which f returns true.

Practice

Given temps = [12.5, 18.0, 23.4, 9.1, 30.2], print the average, the temperatures above 15 (with filter), and the list converted to Fahrenheit (c * 9 / 5 + 32) with a comprehension.

Show solution
temps = [12.5, 18.0, 23.4, 9.1, 30.2]
println(sum(temps) / length(temps))
println(filter(t -> t > 15, temps))
println([c * 9 / 5 + 32 for c in temps])
18.64
[18.0, 23.4, 30.2]
[54.5, 64.4, 74.12, 48.379999999999995, 86.36]