# How do you unfold a nested Julia array?

**URL:** <https://discourse.julialang.org/t/how-do-you-unfold-a-nested-julia-array/2243>\
**Category:** General Usage\
**Tags:** question\
**Created:** [February 23, 2017, 12:57am UTC](https://discourse.julialang.org/t/how-do-you-unfold-a-nested-julia-array/2243 "2017-02-23T00:57:13Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![juliohm](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/juliohm/32/215266_2.png) [@juliohm](https://discourse.julialang.org/u/juliohm)\
**Post date:** [February 23, 2017, 12:57am UTC](https://discourse.julialang.org/t/how-do-you-unfold-a-nested-julia-array/2243/1 "2017-02-23T00:57:13Z")

</div>

What is an efficient, elegant, Julian way to unfold a nested array:

```julia
nested = [[1,2,3],[4,5]]
vcat(nested...) # works but not always

```

Is there a function in Base to unfold all sorts of nested data structures into a plain list of items?

---

<div class="post-metadata">

**Author:** ![fengyang.wang](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fengyang.wang/32/104_2.png) [@fengyang.wang](https://discourse.julialang.org/u/fengyang.wang)\
**Post date:** [February 23, 2017, 2:16am UTC](https://discourse.julialang.org/t/how-do-you-unfold-a-nested-julia-array/2243/2 "2017-02-23T02:16:06Z")

</div>

It sounds like you are looking for `Compat.Iterators.flatten` (i.e. `Base.flatten` in 0.5, `Base.Iterators.flatten` in 0.6).

---

<div class="post-metadata">

**Author:** ![greg\_plowman](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/greg_plowman/32/8100_2.png) [@greg\_plowman](https://discourse.julialang.org/u/greg_plowman)\
**Post date:** [February 23, 2017, 3:46am UTC](https://discourse.julialang.org/t/how-do-you-unfold-a-nested-julia-array/2243/3 "2017-02-23T03:46:44Z")

</div>

It seems that `flatten()` returns an iterator, so you might need `collect(flatten())`.

Also it seems `flatten()` works for only 1 nested level.  
If you need to flatten deeper nested levels, then something recursive might work:

```julia
function unfold(A)
    V = []
    for x in A
        if x === A
            push!(V, x)
        else
            append!(V, unfold(x))
        end
    end
    V
end

```

Totally untested, but seems to work for the following:

```julia
a = ((1,),2)
b = 3:4
c = [5,[6,[7,8]],9]
A = (a,b,c)
unfold(A)

```

---

<div class="post-metadata">

**Author:** ![stst](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stst/32/17252_2.png) [@stst](https://discourse.julialang.org/u/stst)\
**Post date:** [February 23, 2017, 7:27am UTC](https://discourse.julialang.org/t/how-do-you-unfold-a-nested-julia-array/2243/4 "2017-02-23T07:27:27Z")

</div>

Maybe this?  
[https://gist.github.com/ivirshup/e9148f01663278ca4972d8a2d9715f72](https://gist.github.com/ivirshup/e9148f01663278ca4972d8a2d9715f72)

---

<div class="post-metadata">

**Author:** ![juliohm](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/juliohm/32/215266_2.png) [@juliohm](https://discourse.julialang.org/u/juliohm)\
**Post date:** [February 23, 2017, 8:01am UTC](https://discourse.julialang.org/t/how-do-you-unfold-a-nested-julia-array/2243/5 "2017-02-23T08:01:51Z")

</div>

Thanks @greg_plowman, I marked @fengyang.wang answer as the solution in Base, but it is good to have your solution for multi-level nested structures too.

---

<div class="post-metadata">

**Author:** ![juliohm](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/juliohm/32/215266_2.png) [@juliohm](https://discourse.julialang.org/u/juliohm)\
**Post date:** [February 23, 2017, 8:03am UTC](https://discourse.julialang.org/t/how-do-you-unfold-a-nested-julia-array/2243/6 "2017-02-23T08:03:11Z")

</div>

Thanks @stst, I believe @greg_plowman solution does the same and works for other types other than Arrays.

---

<div class="post-metadata">

**Author:** ![singularitti](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/singularitti/32/17678_2.png) [@singularitti](https://discourse.julialang.org/u/singularitti)\
**Post date:** [September 9, 2018, 7:56pm UTC](https://discourse.julialang.org/t/how-do-you-unfold-a-nested-julia-array/2243/7 "2018-09-09T19:56:35Z")

</div>

My way of doing this:

```julia
function deepflatten(arr)
    dim = [1]

    function recursiveflatten(arr, dim)
        if isa(arr, Vector{<: Vector})
            recursiveflatten(
                collect(Iterators.flatten(arr)),
                pushfirst!(dim, length(arr) / prod(dim))
            )
        else
            arr, pushfirst!(dim, length(arr) / prod(dim))
        end
    end

    flattened, dim = recursiveflatten(arr, dim)
    reshape(flattened, dim[1:end-1]...)
end

```

---

<div class="post-metadata">

**Author:** ![anandj](https://avatars.discourse-cdn.com/v4/letter/a/e495f1/32.png) [@anandj](https://discourse.julialang.org/u/anandj)\
**Post date:** [June 3, 2022, 5:36pm UTC](https://discourse.julialang.org/t/how-do-you-unfold-a-nested-julia-array/2243/8 "2022-06-03T17:36:58Z")

</div>

For arbitrary nesting like `x = [[1,2], [3, [4, [5]]]]`, what I ended up doing was

```julia
using AbstractTrees
x = [[1, 2], [3, [4, [5]]]]
v = collect(Leaves(x)) # [1, 2, 3, 4, 5]

```

---

<div class="post-metadata">

**Author:** ![rafael.guerra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rafael.guerra/32/216610_2.png) [@rafael.guerra](https://discourse.julialang.org/u/rafael.guerra)\
**Post date:** [June 4, 2022, 4:04pm UTC](https://discourse.julialang.org/t/how-do-you-unfold-a-nested-julia-array/2243/9 "2022-06-04T16:04:42Z")

</div>

In Rosetta code there is a [fast solution](https://rosettacode.org/wiki/Flatten_a_list#Julia):

```julia
flat(arr) = mapreduce(x -> x == [] || x[1] === x ? x : flat(x), vcat, arr, init=[])

x = [[1,2], [3, [4, [5]]]]
y = ((1,2), (3, (4, (5))))
z = (((1,),2), 3:4, [5,[6,[7,8]],9])
w = (("ab", 'c'), 1:3)

flat(x)
flat(y)
flat(z)
flat(w)

```

---

<div class="post-metadata">

**Author:** ![rocco\_sprmnt21](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rocco_sprmnt21/32/20127_2.png) [@rocco\_sprmnt21](https://discourse.julialang.org/u/rocco_sprmnt21)\
**Post date:** [June 4, 2022, 11:15pm UTC](https://discourse.julialang.org/t/how-do-you-unfold-a-nested-julia-array/2243/10 "2022-06-04T23:15:54Z")

</div>

```julia
using IterTools
flatn(w)=collect(nth(iterated(Base.Flatten,w),length(split(string(w),['[','(']))))

```

---

<div class="post-metadata">

**Author:** ![JeffreySarnoff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeffreysarnoff/32/1980_2.png) [@JeffreySarnoff](https://discourse.julialang.org/u/JeffreySarnoff)\
**Post date:** [June 6, 2022, 6:00pm UTC](https://discourse.julialang.org/t/how-do-you-unfold-a-nested-julia-array/2243/11 "2022-06-06T18:00:38Z")

</div>

If you have a nested Tuple, where all elements are values or Tuples (not vectors),  
this is a performant and memory respectful solution. As written, it returns a Vector. To obtain a tuple, use  
`result = Tuple(flattener(nestedtuples))`

```julia
using TupleTools

function flattener(x)
  y = TupleTools.flatten(x)
  n = sum(length.(y))
  z = Vector{Any}(undef, n)
  i=1; for k in y
      if isa(k, Tuple)
         for r in k
             z[i] = r
         end
      else
         z[i] = k
      end
      i += 1
   end
   z
end

```

---

<div class="post-metadata">

**Author:** ![rocco\_sprmnt21](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rocco_sprmnt21/32/20127_2.png) [@rocco\_sprmnt21](https://discourse.julialang.org/u/rocco_sprmnt21)\
**Post date:** [June 11, 2022, 10:01am UTC](https://discourse.julialang.org/t/how-do-you-unfold-a-nested-julia-array/2243/12 "2022-06-11T10:01:36Z")

</div>

> [@JeffreySarnoff](#):
>
> `TupleTools.flatten`

if I understand correctly this function is based on something like the following.  
Why can’t it also apply to generic vectors?

```julia
flat(x::Any)=(x,)
flat(t::Tuple{}) = ()
flat(t::Tuple)=(flat(t[1])...,flat(Base.tail(t))...)

```

---

<div class="post-metadata">

**Author:** ![rocco\_sprmnt21](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rocco_sprmnt21/32/20127_2.png) [@rocco\_sprmnt21](https://discourse.julialang.org/u/rocco_sprmnt21)\
**Post date:** [June 11, 2022, 2:02pm UTC](https://discourse.julialang.org/t/how-do-you-unfold-a-nested-julia-array/2243/13 "2022-06-11T14:02:58Z")

</div>

this one (which I’ve come to by trial and error) seems to work for nested vectors.  
I have tried in vain to reproduce a method for dispatching on empty vectors in a way equivalent to that for empty tuples.

```julia

flav(x::Union{Real, String, Char})=x
flav(v :: AbstractArray)=[flav(v[1])...,(isempty(v[2:end]) ? [] : flav(v[2:end]))...]

v=[1.,'b']
v1=[11,v]
flav(v1)

v2=[[1,"abc"],v1]
v3=[[3,[31,32]],v2]
flav(v3)

v4=[v2,[v1,v3]]

flav(v4)   

```
