Append! on arrays of arryas

I want to create an array of empty arrays so I can append and have different sized arrays like this:

But, if I use fill to create the array of empty arrays and then I append it the result is this:

Why is it any different when initializing the array of arrys with fill? Does it have to do with how it saves to memory?

I found out how to initialize my array of a given number of arryays like this:

for n in 1:N

Doing it like this allows me to append it the way I want.

In the fill example, you are creating a single array pointing to some memory on the heap. This is passed into the fill function and sets every element pointing at that same array.

To get what you want, you have to create a new array for each element, e.g. with a list comphrension:

arr=[[] for _ in 1:10]

The Julia documentation for the fill() covers this explicitly.
?fill in the Julia REPL will show you this. It is also available
in the online Julia documentation.

1 Like

If you don’t want to stick to a predefined size, you could use a schema like this …

julia> arr2=Vector{Int64}[]

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

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

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

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

julia> arr2
2-element Vector{Vector{Int64}}:


I am not responsible for any adverse side effects

Btw this is going to have some pretty bad performances depending on what you actually want to do

Ah, thank you!