Looping over nested structures
You've seen how you can loop over a vector to return the values within that vector. One step further than this is to loop over a vector of vectors, returning the corresponding values in order. This can be referred to as a 'nested' structure, where one vector is inside another vector. You'll often find nested structures in practice, so understanding how to iterate over these structures and extract data from them is an important skill to have.
In this example, we have changed our previous stock_tickers
vector to include the current stock price of each ticker, and we have renamed the vector to stocks
. Note the structure of the nested vector below.
4-element Vector{Vector{Any}}:
["AAPL", 151]
["AMZN", 94]
["GOOG", 97]
["MSFT", 241]
This exercise is part of the course
Intermediate Julia
Exercise instructions
- Loop over the nested vector
stocks
to return the stock ticker and price for each ticker in the vector.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Loop over stocks, printing the ticker and the price
for (ticker, price) in ____
println("The price of 1 ____ share is ____.")
end