zip
.. zip(iters...)
For a set of iterable objects, returns an iterable of tuples, where the ``i``\ th tuple contains the ``i``\ th component of each input iterable.
Note that :func:`zip` is its own inverse: ``collect(zip(zip(a...)...)) == collect(a)``.
Examples
julia> a = [1,2,3];
julia> b = [4,5,6,7];
julia> foo = zip(a, b);
julia> for i in foo
print(i)
end
(1,4)(2,5)(3,6)
julia> # 7 not paired
The zip
function in Julia takes multiple iterables and returns an iterable of tuples. Each tuple contains the corresponding elements from each input iterable.
julia> a = [1, 2, 3];
julia> b = [4, 5, 6];
julia> c = [7, 8, 9];
julia> zipped = zip(a, b, c)
Base.Iterators.Zip{Tuple{Array{Int64,1},Array{Int64,1},Array{Int64,1}}}((a, b, c))
-
Iterate over the zipped values:
julia> for (x, y, z) in zipped println(x, ", ", y, ", ", z) end 1, 4, 7 2, 5, 8 3, 6, 9
This example demonstrates how to iterate over the zipped values and print each element.
-
Collect the zipped values into an array of tuples:
julia> collected = collect(zipped) 3-element Array{Tuple{Int64,Int64,Int64},1}: (1, 4, 7) (2, 5, 8) (3, 6, 9)
It collects the zipped values into an array of tuples.
- Inverse operation of
zip
:julia> collected2 = collect(zip(zip(a...)...)) 3-element Array{Tuple{Int64,Int64,Int64},1}: (1, 2, 3) (4, 5, 6) (7, 8, 9)
This example demonstrates that
zip
is its own inverse by zipping the previously zipped values again.
Note: The zip
function returns an iterator, so it can be used in a lazy manner without collecting all the tuples at once.
Please let me know if you have any further questions.
See Also
countfrom, cycle, done, drop, eachindex, enumerate, first, repeated, rest, start, svds, take, vecdot, vecnorm, zip,User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.