push!
.. push!(collection, items...) -> collection
Insert one or more ``items`` at the end of ``collection``.
.. doctest::
julia> push!([1, 2, 3], 4, 5, 6)
6-element Array{Int64,1}:
1
2
3
4
5
6
Use :func:`append!` to add all the elements of another collection to
``collection``.
The result of the preceding example is equivalent to
``append!([1, 2, 3], [4, 5, 6])``.
Examples
julia> a= Int64[]
push!(a,1)
push!(a,2)
2-element Array{Int64,1}:
1
2
julia> foo = [1,2,3];
julia> push!(foo, 4, 5, 6);
julia> foo
6-element Array{Int64,1}:
1
2
3
4
5
6
The push!(collection, items...)
function in Julia is used to insert one or more items
at the end of the collection
.
julia> push!([1, 2, 3], 4, 5, 6)
6-element Array{Int64,1}:
1
2
3
4
5
6
Here are some common examples of using push!
:
-
Add elements to an array:
julia> arr = [1, 2, 3]; julia> push!(arr, 4, 5) 5-element Array{Int64,1}: 1 2 3 4 5
This example inserts the elements 4 and 5 at the end of the array
arr
. -
Append elements from another collection:
julia> original = [1, 2, 3]; julia> additional = [4, 5]; julia> push!(original, additional...) 5-element Array{Int64,1}: 1 2 3 4 5
The
...
syntax is used to unpack the elements from theadditional
collection and insert them at the end of theoriginal
collection. - Add elements to an empty collection:
julia> empty_collection = Int[] julia> push!(empty_collection, 1, 2, 3) 3-element Array{Int64,1}: 1 2 3
In this example, elements are added to an initially empty collection.
It's important to note that push!
modifies the original collection and returns the modified collection itself.
To add all the elements of another collection to an existing collection, you can use the append!
function. The result of the preceding example using push!
is equivalent to append!([1, 2, 3], [4, 5, 6])
.
See Also
append!, delete!, deleteat!, empty!, endof, filter, filter!, gc, get!, getkey, haskey, insert!, isempty, keys, map, map!, merge, merge!, pop!, prepend!, push!, reduce, resize!, shift!, splice!, unshift!, values,User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.