Member-only story

Ranges and Slices in Julia and Python

Using ranges to get or set parts of an array

Erik Engheim
5 min readMar 9, 2019

Ranges can look quite similar in both Python and Julia, however the apparent similarity can be deceptive as they work entirely different.

Here is an example of creating an array and accessing a subset of it in Julia. Notice that Julia has 1-based indices, meaning first element is at index 1.

julia> a = [2, 4, 6, 8]
julia> a[2:4]
3-element Array{Int64,1}:
4
6
8

The example in Python looks very similar:

python> a = [2, 4, 6, 8]
python> a[2:4]
[6, 8]

Julia Ranges

But here is where it starts getting different. In Julia : is an operator just like + or -. Operators in Julia are just syntax sugar for function calls. So 3 + 4 in Julia is just syntax sugar for +(3, 4), to avoid ambiguity one writes (+)(3, 4). Thus in Julia 2:4 is the same as writing (:)(2,4).

This has implications for how we use it. In Julia I can put a range into an object using the colon syntax:

julia> r = 2:4
2:4

julia> a[r]
3-element Array{Int64,1}:
4
6
8

julia> typeof(r)
UnitRange{Int64}

julia> r.start
2

julia> r.stop
4

If we check the step, you can see that does not exist for a UnitRange.

julia> r.step
ERROR: type UnitRange has no field step

--

--

Erik Engheim
Erik Engheim

Written by Erik Engheim

Geek dad, living in Oslo, Norway with passion for UX, Julia programming, science, teaching, reading and writing.

No responses yet