Unzip an array of tuples in julia

For larger arrays use @ivirshup's solution below.

For smaller arrays, you can use zip and splitting.

You can achieve the same thing in Julia by using the zip() function (docs here). zip() expects many tuples to work with so you have to use the splatting operator ... to supply your arguments. Also in Julia you have to use the collect() function to then transform your iterables into an array (if you want to).

Here are these functions in action:

arr = [(1,2), (3,4), (5,6)]

# wtihout splatting
collect(zip((1,2), (3,4), (5,6)))

# Output is a vector of arrays:
> ((1,3,5), (2,4,6))

# same results with splatting
collect(zip(arr...))
> ((1,3,5), (2,4,6))

As an alternative to splatting (since that's pretty slow), you could do something like:

unzip(a) = map(x->getfield.(a, x), fieldnames(eltype(a)))

This is pretty quick.

julia> using BenchmarkTools
julia> a = collect(zip(1:10000, 10000:-1:1));
julia> @benchmark unzip(a)
BenchmarkTools.Trial: 
  memory estimate:  156.45 KiB
  allocs estimate:  6
  --------------
  minimum time:     25.260 μs (0.00% GC)
  median time:      31.997 μs (0.00% GC)
  mean time:        48.429 μs (25.03% GC)
  maximum time:     36.130 ms (98.67% GC)
  --------------
  samples:          10000
  evals/sample:     1

By comparison, I have yet to see this complete:

@time collect(zip(a...))

Tags:

Julia