Unpack unknown number of values

Is it possible to unpack an unknown number of values, something like this?

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

julia> x
2

What version is that? I’m on 1.5.4.

julia> _, x, _... = [1,2, 3]
ERROR: syntax: invalid assignment location "_..." around REPL[26]:1

I’m on v1.6.0. LHS slurping was introduced here: https://github.com/JuliaLang/julia/pull/37410

3 Likes

You can also leave out the remaining values, like this:

_, x = [1,2,3]

Huh, that’s not what I expected.

It is strange, but what happens is that for each identifier on the right, Julia iterates the object in the left side and save the value to the corresponding identifier, so:

  1. You can unpack anything that answers to iterate (even your own types, if you define iterate for them).
  2. The number of identifiers in the right side cannot be greater than the number of elements in the left side object.
1 Like