Chapter 10. Arrays

This chapter presents one of Julia’s most useful built-in types, the array. You will also learn about objects and what can happen when you have more than one name for the same object.

An Array Is a Sequence

Like a string, an array is a sequence of values. In a string, the values are characters; in an array, they can be any type. The values in an array are called elements or sometimes items.

There are several ways to create a new array; the simplest is to enclose the elements in square brackets ([ ]):

[10, 20, 30, 40]
["crunchy frog", "ram bladder", "lark vomit"]

The first example is an array of four integers. The second is an array of three strings. The elements of an array don’t have to be the same type. The following array contains a string, a float, an integer, and another array:

["spam", 2.0, 5, [10, 20]]

An array within another array is nested.

An array that contains no elements is called an empty array; you can create one with empty brackets, [].

As you might expect, you can assign array values to variables:

julia> cheeses = ["Cheddar", "Edam", "Gouda"];

julia> numbers = [42, 123];

julia> empty = [];

julia> print(cheeses, " ", numbers, " ", empty)
["Cheddar", "Edam", "Gouda"] [42, 123] Any[]

The function typeof can be used to find out the type of the array:

julia> typeof(cheeses)
Array{String,1}
julia> typeof(numbers)
Array{Int64,1}
julia> typeof(empty)
Array{Any,1}

The number indicates the dimensions (we’ll talk more about this in “Arrays”). The array ...

Get Think Julia now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.