Julia Arrays
An array is an ordered collection of values stored in one variable. Each value sits at a numbered position, called an index, and the first index is 1.
An array prints its values in order
Square brackets build an array of values. A second array mixes a number, a string, and a Bool.
scores = [3, 1, 4]
println(scores)
println(length(scores))
println([1, "one", true])Indexes read single values
Index 1 reads the first value. The keyword end inside the brackets reads the last value.
nums = [10, 20, 30]
println(nums[1])
println(nums[2])
println(nums[end])An assignment changes one item
Assigning to an index replaces the value stored there. The rest of the array stays the same.
nums = [3, 1, 4]
nums[2] = 9
println(nums)
println(nums[2])Example
temps = [21, 19, 23, 20]
temps[2] = 18
println(temps)
println(temps[1])
println(temps[end])
println(length(temps))Key points
- Array literal: values in square brackets, separated by commas, like [1, 2, 3].
- Index: the position of a value in an array, counted from 1.
- Reading: a[1] gives the first value and a[end] gives the last value.
- Changing: a[2] = 9 replaces the value stored at index 2.
- Length: length(a) gives how many values the array holds.
- Mixed values: one array can hold simple values of different types, like 1 and "one".
In this example, temps starts with four readings and the assignment temps[2] = 18 replaces the second one. The prints then show the updated array, its first value 21, its last value 20, and its length 4.
Note
Julia indexes from 1, while some other languages index from 0.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What does [5, 6, 7][2] give?