Create array of empty (separate) vectors

I want to initialise a number of (in this case empty) vectors. However, if I do e.g.

x = fill([],4)
push!(x[1],3)
x[2]

I get [3]. Basically, I put in the same vector 4 times, so now when I modify one, I modify all.

What is the workaround for this?

x = [ [] for in in 1:4 ] should work.

1 Like

thanks :slight_smile:

You should probably add a type annotation to your vectors. E.g.

x = [ Int[] for in in 1:4 ]
4 Likes
julia> vov=Vector{Vector{Int}}()
Vector{Int64}[]

julia> push!(vov,[],[],[])
3-element Vector{Vector{Int64}}:
 []
 []
 []

julia> vov
3-element Vector{Vector{Int64}}:
 []
 []
 []

julia> 

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

julia> vov
3-element Vector{Vector{Int64}}:
 []
 [22]
 []

 vov=Vector{Vector{Int}}()
foreach(_->push!(vov,[]),1:4)

This creates three Vector{Any} that are subsequently converted to Vector{Int}. Is that efficient?