Reading Collections

Last updated: January 12, 2023

 Table of contents

Tuples

Immutable, indexable, possibly heterogeneous collections of elements:

typeof((2, 4, 1.0, "test"))
(2, 4, 1.0, "test")[2]

Named tuples

Tuples can have named components:

typeof((a=2, b=4, c=1.0, d="test"))

x = (a=2, b=4, c=1.0, d="test");
x[4] == x.d

Dictionaries

Similarly to Python, Julia has dictionaries: associative collections of key/value pairs:

Dict("a"=>1, "b"=>2, "c"=>3)

Arrays

Arrays are mutable, indexable, homogeneous collections of elements.

One dimension

Unidimensional arrays of one element:

[3]
[3.4]
["Hello, World!"]

Unidimensional arrays of multiple elements:

[3, 4]

Arrays are homogeneous collections, but look how Julia's abstract types make the following array possible:

[3, "hello"]

These 4 syntaxes are equivalent:

[2
4
8]
[2; 4; 8]
vcat(2, 4, 8)
cat(2, 4, 8, dims=1)

Two dimensions

[3 4]
[[1, 3] [1, 2]]

These 3 syntaxes are equivalent:

[2 4 8]
hcat(2, 4, 8)
cat(2, 4, 8, dims=2)

Syntax subtleties

Elements separated by semi-colons or end of line get expanded vertically. Those separated by commas do not get expanded. Elements separated by spaces or tabs get expanded horizontally.

Compare the outputs of the following:

[1:2; 3:4]

[1:2
 3:4]

[1:2, 3:4]

[1:2 3:4]

Initializing arrays

Here are a few of the functions initializing arrays:

rand(2, 3, 4)
rand(Int64, 2, 3, 4)
zeros(Int64, 2, 5)
ones(2, 5)
reshape([1, 2, 4, 2], (2, 2))
fill("test", (2, 2))

Comprehensions

Julia has comprehensions similar to Python:

[ 3i + j for i=1:10, j=3 ]

Indexing

As in other mathematically oriented languages such as R, Julia starts indexing at 1.
Indexing is done with square brackets:

a = [1 2; 3 4]
a[1, 1]
a[1, :]
a[:, 1]

Index the element on the 3rd row and 2nd column of b :

b = ["wrong" "wrong" "wrong"; "wrong" "wrong" "wrong"; "wrong" "you got it" "wrong"]

As in Python, by default, arrays are passed by sharing:

a = [1, 2, 3];
a[1] = 0;
a

This prevents the unwanted copying of arrays.

Comments & questions