user11803410
user11803410

Reputation: 35

properly creating arrays of arrays in julia

i would like to populate an array of arrays with integers in julia. the following works:

a = Array{Int64}[]
push!(a, [1,2,3])

but this doesn't:

a = Array{Array{Int64}}[]
push!(a, [1, 2, 3])

the error is: MethodError: Cannot `convert` an object of type Int64 to an object of type Array{Int64,N} where N

can someone explain why? it seems like Array{Array{Int64}} should be the type of array whose elements are arrays containing Int64 values whereas Array{Int64} is an array of integers. yet a = Array{Int64}[] seems to initialize an array of arrays containing integers and not an array of integers? can someone clarify the logic here?

Upvotes: 3

Views: 2079

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69949

In

a = Array{Int64}[]
push!(a, [1,2,3])

is a vector of arrays and after the operation you have a 1-element vector containing one array:

julia> a
1-element Array{Array{Int64,N} where N,1}:
 [1, 2, 3]

julia> a[1]
3-element Array{Int64,1}:
 1
 2
 3

While:

a = Array{Array{Int64}}[]

creates you a vector of arrays of arrays:

julia> a = Array{Array{Int64}}[]
0-element Array{Array{Array{Int64,N} where N,N} where N,1}

so you can push! into it arrays of arrays, e.g.:

julia>     push!(a, [[1,2,3]])
1-element Array{Array{Array{Int64,N} where N,N} where N,1}:
 [[1, 2, 3]]

julia> a[1]
1-element Array{Array{Int64,N} where N,1}:
 [1, 2, 3]

julia> a[1][1]
3-element Array{Int64,1}:
 1
 2
 3

Upvotes: 3

Related Questions