For loops

Intermediate Julia

Anthony Markham

Quantitative Developer

Course outline

  • Control Structures

  • Advanced Data Structures

  • Advanced Functions in Julia

  • DataFrame Operations and Extensibility

Intermediate Julia

For loops - introduction

  • A loop is a way to repeat a set of actions a known number of times.
for variable in iterable
    expression
end
shopping_list = ["Apples", "Bread", "Carrots", "Strawberries"]
println(shopping_list)
["Apples", "Bread", "Carrots", "Strawberries"]
Intermediate Julia

Repeating single commands

  • Accessing each element of the structure via indexing is messy and not practical.
println(shopping_list[1])
println(shopping_list[2])
println(shopping_list[3])
println(shopping_list[4])
Intermediate Julia

For loops - the structure

  • For loops allow us to simplify the process of extracting data from a structure
  • The iterable is shopping_list
  • The iterator is item, an arbitrary name
for item in shopping_list
    println(item)
end
Apples
Bread
Carrots
Strawberries
Intermediate Julia

Iterating through the shopping list

  • For loops allow us to simplify the process of extracting data from a structure
  • The iterable is shopping_list
  • The iterator is item, an arbitrary name
for item in shopping_list
    println(item)
    # first iteration, item = 'Apples'
end
Apples
Intermediate Julia

Iterating through the shopping list

  • For loops allow us to simplify the process of extracting data from a structure
  • The iterable is shopping_list
  • The iterator is item, an arbitrary name
for item in shopping_list
    println(item)
    # second iteration, item = 'Bread'
end
Apples
Bread
Intermediate Julia

Iterating through the shopping list

  • For loops allow us to simplify the process of extracting data from a structure
  • The iterable is shopping_list
  • The iterator is item, an arbitrary name
for item in shopping_list
    println(item)
    # third iteration, item = 'Carrots'
end
Apples
Bread
Carrots
Intermediate Julia

Iterating through the shopping list

  • For loops allow us to simplify the process of extracting data from a structure
  • The iterable is shopping_list
  • The iterator is item, an arbitrary name
for item in shopping_list
    println(item)
    # fourth iteration, item = 'Strawberries'
end
Apples
Bread
Carrots
Strawberries
Intermediate Julia

Enumerate

  • The enumerate function allows us to return an index and value pair when iterating over a data structure.
for (index, item) in enumerate(shopping_list)
    println(index, " ", item)
end
1Apples
2Bread
3Carrots
4Strawberries
shopping_list = ["Apples", "Bread", "Carrots", "Strawberries"]
Intermediate Julia

Let's practice!

Intermediate Julia

Preparing Video For Download...