1

So basically I wrote this code:

a = [[], [], []]   # a is an array of array

#### there is some code that modified a, then I want to clear array a ####

fill!(a, [])       # set every element of a back to an empty array
push!(a[1], 1)     # modify one of the element
println(a)

And then, the output becomes:

[[1], [1], [1]]

This means the code fill!(a, []) actually fills the same array reference to every index in a.

Is this a bug in Julia? If this method doesn't work, what alternative solution do I have?

2
  • See comments of this question to shed light on this behavior. Commented Jan 14, 2023 at 20:44
  • Keep in mind that [] is the same as Any[], which creates a Vector{Any}. This means your code will be slow. If you know the element type of the inner vectors, specify them. E.g. [Int[] for _ in 1:3]. Commented Jan 15, 2023 at 9:28

3 Answers 3

2

Playing around, the following seems to work also:

v .= copy.(fill!(v,[]))

It is closer to the original use of fill!, but I've never seen it used before and so it is more of a curiousity than idiomatic Julia.

NOTE:

Appreciating the enthusiasm for this answer, I must mention that [ [] for _ in 1:3 ] is the faster way of getting this done. Another method is map(_ -> [], 1:3). Another really nice and efficient method is:

map!(_ -> [], v, v)
Sign up to request clarification or add additional context in comments.

Comments

2

As Ahmed says, it's not a bug. In fill!(a, []) you only create a single array reference, which you store in every slot of a. To create a you can either use a= [ [], [], [] ], or slightly more readable:

a = [ [] for _ in 1:3 ].

To clean out every entry you can use broadcasting of the function empty!, i.e. call empty! on every element of a:

empty!.(a)

This avoids creating any new arrays.

Comments

1

this is not a bug even in other programming languages the fill method works the same.

if you want to clean your array you can simply clean it just like the declaration :

a = [[], [], []]  

and if the length can be changed you can use for i in 1: length(a) and clean each item

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.