team17
team17

Reputation: 816

Creating an Array of Arrays in Julia

I'm trying to create an array of arrays of a special type in Julia.

For example, I want to create a list that saves lists (arrays) of integer values.

I need to know how to:

  1. Initialize an (empty) list for the arrays
  2. Use append!/push! to add an array of a specific data structure (in this case integer arrays) to the list

I think this is a very easy question (and is probably answered somewhere in the documentation), but my previous research confuses me more and more.

Is there a difference between:

List = Int64[]

and

List = Array{Int64,1}

Something like this does not work for me:

ListOfList = Int64[Int64]
ListOfList = Array{Int64[],1}
ListOfList = Array{Array{Int64,1},1}

Upvotes: 3

Views: 6541

Answers (1)

Alex A.
Alex A.

Reputation: 5586

You can construct your array of arrays like so:

# Initialize an array that can contain any values
listOfLists = Any[]

# Push some arrays into the array
push!(listOfLists, [1, 2, 3])
push!(listOfLists, [4, 5])
push!(listOfLists, ["Julia", "rocks"])

# You now have an array containing arrays
listOfLists
# 3-element Array{Any,1}:
#  [1,2,3]                     
#  [4,5]                       
#  ASCIIString["Julia","rocks"]

To answer your question regarding the difference in initialization, consider the following.

List = Int64[]
typeof(List)
# Array{Int64,1}

List = Array{Int64,1}
typeof(List)
# DataType

The former is actually initializing List to be a 1-dimensional array containing integer values, whereas the latter is setting List to be the type Array{Int64,1}.

Upvotes: 8

Related Questions