Appending a vector to a vector of vectors

Iā€™m trying to create an empty vector of vectors and then append vectors to it so that I end up with a ragged array. What is wrong with this code?

julia> a = Vector{Vector{Int}}[]
Vector{Vector{Int64}}[]

julia> x = [1,2]
2-element Vector{Int64}:
 1
 2

julia> append!(a, copy(x))
ERROR: MethodError: Cannot `convert` an object of type Int64 to an object of type Vector{Vector{Int64}}

Thanks

julia> a = Vector{Int}[]
Vector{Int64}[]

julia> push!(a, [1,2]);

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

this is a Vector of Vector{Vector{Int}}, not a Vector of Vector. In order to add a single element to the collection, you want to use push!() not append!()


lastly, I would recommend using: GitHub - JuliaArrays/ArraysOfArrays.jl: Efficient storage and handling of nested arrays in Julia if your code is performance critical

1 Like

What you created is a

julia> x = Vector{Vector{Int64}}[]
Vector{Vector{Int64}}[]

julia> typeof(x)
Vector{Vector{Vector{Int64}}} (alias for Array{Array{Array{Int64, 1}, 1}, 1})

So one Vector too much.

I want to end up with a ragged array like:

[[1,2],[3,4,5]]
2-element Vector{Vector{Int64}}:
 [1, 2]
 [3, 4, 5]

But starting with an empty array and pushing one vector at a time.

That solves the problem:

julia> a = Vector{Vector{Int}}()
Vector{Int64}[]

julia> typeof(a)
Vector{Vector{Int64}} (alias for Array{Array{Int64, 1}, 1})

julia> push!(a, [1,2])
1-element Vector{Vector{Int64}}:
 [1, 2]

I needed ā€œ()ā€ rather than ā€œā€. Thanks.

just continue with my example?

julia> a = Vector{Int}[]
Vector{Int64}[]

julia> push!(a, [1,2]);

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

julia> push!(a, [1,2,3]);

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

this is same as a = Vector{Int}[], because:

T[]

is equivalent to:

Vector{T}()
1 Like

Much cleaner. Thank you.