Is there a way to unpack like a,*rest=[1,2,3,4] in python?

Hi, I’m trying to migrate a python program to Julia, I find array unpacking very convenient. I wonder is there something similar in Julia?

In python we can write

a=[1,2,3,4,5]
b,*p=a

then b=1 and p=[2,3,4,5]

and similarly

a=[1,2,3,4,5,6,7]
*p, b=a

then p=[1,2,3,4,5,6] and b=7

Is there similar thing in Julia?
Thanks

1 Like

There is not: https://github.com/JuliaLang/julia/issues/2626.

1 Like

It’s not the prettiest syntax, but you can do

julia> import Pkg; Pkg.add("Match");

julia> using Match

julia> a = [1,2,3,4,5]
5-element Array{Int64,1}:
 1
 2
 3
 4
 5

julia> @match(a, [b, p..., y])
(1, [2, 3, 4], 5)

julia> b
1

julia> p
3-element view(::Array{Int64,1}, 2:4) with eltype Int64:
 2
 3
 4

julia> y
5

It also should be possible to create a macro that would handle the syntax proposed in https://github.com/JuliaLang/julia/issues/2626.

Cheers,
Kevin

1 Like

Of course, you can do

b = a[1]
p = a[2:end]

and so on, so there is a way to unpack this, but no special syntax (without using macros).

You don’t need macros or special syntax for this, just a trivial mini-function.

splitfirst(x) = x[1], x[2:end]
a = 1:5
b, p = splitfirst(a)