An array of empty arrays


#1

Is this the best, or only, way to do this ?

julia> a=Array{Any,1}(5)
5-element Array{Any,1}:
 #undef
 #undef
 #undef
 #undef
 #undef

julia> fill!(a,[])
5-element Array{Any,1}:
 Any[]
 Any[]
 Any[]
 Any[]
 Any[]

just curious. I would have done this in python with

[[]]*5


#2
julia> [[] for i=1:5]
5-element Array{Array{Any,1},1}:
 Any[]
 Any[]
 Any[]
 Any[]
 Any[]

#3

What you have is identical to

julia> fill([], 5)
5-element Array{Array{Any,1},1}:
 Any[]
 Any[]
 Any[]
 Any[]
 Any[]

Note that the arrays you filled in are the same one (i.e. same as [[]] * 5 in python).


#4

As @yuyichao alluded to, there is a difference between the fill and comprehension techniques: do you want an array of the same empty array, or an array of different empty arrays? This will affect what happens if you modify one of the arrays:

julia> a = fill([], 5)
5-element Array{Array{Any,1},1}:
 Any[]
 Any[]
 Any[]
 Any[]
 Any[]

julia> push!(a[1], "hello"); a
5-element Array{Array{Any,1},1}:
 Any["hello"]
 Any["hello"]
 Any["hello"]
 Any["hello"]
 Any["hello"]

julia> b = [[] for i=1:5]
5-element Array{Array{Any,1},1}:
 Any[]
 Any[]
 Any[]
 Any[]
 Any[]

julia> push!(b[1], "hello"); b
5-element Array{Array{Any,1},1}:
 Any["hello"]
 Any[]       
 Any[]       
 Any[]       
 Any[]  

Note that the [[]]*5 construct in Python is similar to fill here, in that it makes a list of 5 references to the same empty list:

In [1]: a = [[]]*5; a
Out[1]: [[], [], [], [], []]

In [2]: a[0].append('hello'); a
Out[2]: [['hello'], ['hello'], ['hello'], ['hello'], ['hello']]

#5

oh my.

I’d forgotten about that distinction even though I had been burned by it in Python.

Yes , I most definitely wanted 5 distinct arrays.

Thank you!