unshift!

unshift!(collection, items...) -> collection

Insert one or more items at the beginning of collection.

  julia> unshift!([1, 2, 3, 4], 5, 6)
  6-element Array{Int64,1}:
   5
   6
   1
   2
   3
   4

Examples

julia> a = [1, 2, 3]
       unshift!(a,7)
4-element Array{Int64,1}:
 7
 1
 2
 3
julia> a = [1, 2, 3]
       unshift!(a,7,2)
5-element Array{Int64,1}:
 7
 2
 1
 2
 3
julia> foo = [1,2,3];

julia> unshift!(foo, 5, 6);

julia> foo
5-element Array{Int64,1}:
 5
 6
 1
 2
 3
  1. Add elements at the beginning of an array:

    julia> arr = [1, 2, 3, 4];
    julia> unshift!(arr, 5, 6)
    6-element Array{Int64,1}:
    5
    6
    1
    2
    3
    4

    This example adds the elements 5 and 6 at the beginning of the array arr.

  2. Prepend elements to a vector of strings:

    julia> words = ["orange", "grape"];
    julia> unshift!(words, "apple", "banana")
    4-element Array{String,1}:
    "apple"
    "banana"
    "orange"
    "grape"

    It adds the elements "apple" and "banana" at the beginning of the vector words.

  3. Handle edge cases when adding to an empty collection:
    julia> numbers = Int[]
    julia> unshift!(numbers, 1)
    1-element Array{Int64,1}:
    1

    It correctly handles the case when the collection is empty by adding the element at the beginning.

Common mistake example:

julia> arr = [1, 2, 3, 4];
julia> unshift!(arr, [5, 6])
ERROR: MethodError: Cannot `convert` an object of type Vector{Int64} to an object of type Int64

In this example, the mistake is providing a vector [5, 6] as the second argument instead of individual elements. The unshift! function expects multiple arguments for the items to be inserted. To fix this, pass each element individually as separate arguments to unshift!.

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.

*Required Field
Details

Checking you are not a robot: