pythonmultidimensional-arrayjuliaiterable-unpacking

How to unpack multidimensional array into variables in Julia


In Python I can do:

a = array([[1,2],[3,4]])
row1, row2 = a

Is there an equivalent one-liner in Julia? This doesn't seem to work:

a = [[1 2]; [3 4]]
row1, row2 = a

Instead it sets row1=1 and row2=3. Thanks!


Solution

  • Depending on what you are doing you could use a Vector{Vector{T}}, like python list of lists instead of a Matrix (Array{T,2}).

    In v0.5+ it just works, with [ , ]:

    julia> VERSION
    v"0.5.0-dev+4440"
    
    julia> a = [[1, 2], [3, 4]]
    2-element Array{Array{Int64,1},1}:
     [1, 2]
     [3, 4]
    
    julia> a = [[1, 2]; [3, 4]]
    4-element Array{Int64,1}:
     1
     2
     3
     4
    
    julia> row1, row2 = a;
    
    julia> (row1, row2)
    (2-element Array{Int64,1}:
     1
     2,2-element Array{Int64,1}:
     3
     4)
    

    In v0.4+ you need to type the array as an array of arrays, like so:

    julia> VERSION
    v"0.4.5"
    
    julia> a = Vector[[1, 2], [3, 4]]
    2-element Array{Array{T,1},1}:
     [1,2]
     [3,4]
    
    julia> b = [[1, 2]; [3, 4]]
    4-element Array{Int64,1}:
     1
     2
     3
     4
    
    julia> c = [[1, 2], [3, 4]]
    WARNING: [a,b] concatenation is deprecated; use [a;b] instead
     in depwarn at deprecated.jl:73
     in oldstyle_vcat_warning at abstractarray.jl:29
     in vect at abstractarray.jl:32
    while loading no file, in expression starting on line 0
    4-element Array{Int64,1}:
     1
     2
     3
     4
    
    julia> row1, row2 = a;
    
    julia> row1, row2
    ([1,2],[3,4])