Ranges

Intermediate Julia

Anthony Markham

Quantitative Developer

Ranges - UnitRange

  • A range is an object, with its own data type.
  • To create a range, we specify a start and stop, both of which are inclusive.
my_range = 1:10  # start:stop
  • Printing a range will not reveal the sequence of values stored within the object!
my_range = 1:10
println(my_range)
1:10
  • The UnitRange is the most basic type of range.
Intermediate Julia

Ranges - StepRange

  • To create a StepRange, we specify a step value, where each element in the range is determined by the step.
my_range = 0:10:50  # start:step:stop
  • The step value determines what the next value in the range will be.
Intermediate Julia

Ranges - StepRange definition

  • Our defined StepRange has:
    • a start value of one
    • a step value of 10
    • an end value of 50
my_range = 1:10:50
println(my_range)
1:10:50
Intermediate Julia

Ranges - for iteration

  • Unpack the values in a range by iterating over the range
  • A for loop can accomplish this, just as we did with a vector
my_range = 0:10:50
for value in my_range
    println(value)
end
0
10
20
30
40
50
Intermediate Julia

Ranges - access

  • Ranges can be accessed by element, just like vectors.
  • start, step, and stop can be used to get the corresponding values for a range.
my_range = 0:10:50
println(my_range[2])
10
Intermediate Julia

Ranges - access

  • Ranges can be accessed by element, just like vectors.
  • start, step, and stop can be used to get the corresponding values for a range.
println(my_range.start)
println(my_range.step)
println(my_range.stop)
0
10
50
Intermediate Julia

Ranges - while iteration

  • Iterating using a while loop requires accessing each individual range element.
  • Ranges use the [] notation to access each element, just like vectors.
  • Note we set i = 1 as Julia starts indexing at 1, not 0!
i = 1

while i <= length(my_range)
    println(my_range[i])
    i = i + 1
end
Intermediate Julia

Ranges - splat unpacking

  • Splat operator ... used to unpack an iterable.
my_range = 0:10:50
println([my_range...])
[0, 10, 20, 30, 40, 50]
  • This is only one simple use case for the splat operator.
Intermediate Julia

Let's practice!

Intermediate Julia

Preparing Video For Download...