Categories: Julia

Loops in Julia

Julia makes only two looping constructs available to you, while and for. In this article, I shall quickly go over them, as they behave as they generally do in other languages.

Looping with While

In general, blocks of code in Julia are terminated with the end keyword. Thus, the indentation of code doesn’t matter.

So, for example, the code below is perfectly valid, albeit a bit hard to read:

julia> i=0;while i<=42
               print(i)
           i+=1
                               end #Following is the output
0123456789101112131415161718192021222324252627282930313233343536373839404142

You can also use break and continue as you would use in any other language:

julia> while true
       print("Ω👌")
       break
       end #Below output shows that this loop runs only once
Ω👌

Looping using for

While while loop is quite vanilla, for loop is where the party’s at, and it has a functional theme, although everyone’s invited. First of all, our usual expectations are satisfied:

julia> for k in 1:42
       print("$k→")
       end #Output below
1→2→3→4→5→6→7→8→9→10→11→12→13→14→15→16→17→18→19→20→21→22→23→24→25→26→27→28→29→30→31→32→33→34→35→36→37→38→39→40→41→42→

But you’re allowed to be more succinct:

julia> for k=1:42
       print("$k→")
       end #Output below
1→2→3→4→5→6→7→8→9→10→11→12→13→14→15→16→17→18→19→20→21→22→23→24→25→26→27→28→29→30→31→32→33→34→35→36→37→38→39→40→41→42→

Moreover, you can do more with the ‘standard library’, like iterating through cartesian products (without having to use additional libraries like itertools):

julia> for m=1:2, k=1:3, l=1:4
    # The following line has a conditional
       if (k==1)&(l==1) println("outermost loop: $m ") end
    # Don't worry if you don't understand it,
    # we'll be discussing them at length soon.
       print("  innermost loop number $l ⟹  " )
       print("k=$k\\n")
       end  #Output below
outermost loop: 1 
  innermost loop number 1 ⟹  k=1
  innermost loop number 2 ⟹  k=1
  innermost loop number 3 ⟹  k=1
  innermost loop number 4 ⟹  k=1
  innermost loop number 1 ⟹  k=2
  innermost loop number 2 ⟹  k=2
  innermost loop number 3 ⟹  k=2
  innermost loop number 4 ⟹  k=2
  innermost loop number 1 ⟹  k=3
  innermost loop number 2 ⟹  k=3
  innermost loop number 3 ⟹  k=3
  innermost loop number 4 ⟹  k=3
outermost loop: 2 
  innermost loop number 1 ⟹  k=1
  innermost loop number 2 ⟹  k=1
  innermost loop number 3 ⟹  k=1
  innermost loop number 4 ⟹  k=1
  innermost loop number 1 ⟹  k=2
  innermost loop number 2 ⟹  k=2
  innermost loop number 3 ⟹  k=2
  innermost loop number 4 ⟹  k=2
  innermost loop number 1 ⟹  k=3
  innermost loop number 2 ⟹  k=3
  innermost loop number 3 ⟹  k=3
  innermost loop number 4 ⟹  k=3

It’s bonus tip time! When testing out loops, it’s quite easy to get your console all cluttered up, so use Ctrl+l to clear the screen (P.S. It actually doesn’t delete the history, but just scrolls a blank line to the top of the terminal).

Finally, one feature that’s easy to overlook but really quite handy is the expressive notation:

julia> for (emoji,word) ∈ Dict("❤️ "=>"Latex","😍"=>"Julia","💯"=>"Machine Learning Geek")
       println("$word is $emoji.")
       end #Output below
Latex is ❤️ .
Machine Learning Geek is 💯.
Julia is 😍.

Note how in can be interchanged with $\\in$. Also, note the order that the sentences are printed in. (Also, in case the first line of the program above seems obscure, it’s simply defining a dictionary, which, along with sets we’ll be discussing soon). We now also have a simple, expressive way of iterating through the characters of a Unicode string:

julia> ASCII="qwrqwr" 
"qwrqwr"

julia> for i=1:6 print(ASCII[i]) end # Our basic approach works due to ASCII chars
qwrqwr
julia> Unicode="Multi-byte:\\u0915 \\u0916"
"Multi-byte:क ख"

julia> for i=1:13 print(Unicode[i]) end #This naive approach won't work
Multi-byte:कERROR: StringIndexError("Multi-byte:क ख", 13)
Stacktrace:
 [1] string_index_err(::String, ::Int64) at ./strings/string.jl:12
 [2] getindex_continued(::String, ::Int64, ::UInt32) at ./strings/string.jl:220
 [3] getindex(::String, ::Int64) at ./strings/string.jl:213
 [4] top-level scope at ./REPL[254]:1

julia> for c∈Unicode print(c) end
Multi-byte:क ख

References

  1. Julia Docs
Editorial Staff

Recent Posts

MapReduce Algorithm

In this tutorial, we will focus on MapReduce Algorithm, its working, example, Word Count Problem,…

7 months ago

Linear Programming using Pyomo

Learn how to use Pyomo Packare to solve linear programming problems. In recent years, with…

1 year ago

Networking and Professional Development for Machine Learning Careers in the USA

In today's rapidly evolving technological landscape, machine learning has emerged as a transformative discipline, revolutionizing…

1 year ago

Predicting Employee Churn in Python

Analyze employee churn, Why employees are leaving the company, and How to predict, who will…

2 years ago

Airflow Operators

Airflow operators are core components of any workflow defined in airflow. The operator represents a…

2 years ago

MLOps Tutorial

Machine Learning Operations (MLOps) is a multi-disciplinary field that combines machine learning and software development…

2 years ago