prepend!

prepend!(collection, items) -> collection

Insert the elements of items to the beginning of collection.

julia> prepend!([3],[1,2])
3-element Array{Int64,1}:
 1
 2
 3

Examples

  1. Prepend elements to an array:

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

    This example adds the elements [1, 2] to the beginning of the array arr.

  2. Prepend elements to a vector of strings:

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

    It adds the elements ["grape", "banana"] to the beginning of the vector of strings.

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

    It correctly handles the case where the collection is initially empty.

Common mistake example:

julia> arr = [5, 10, 15, 20];
julia> prepend!(arr, 7)
ERROR: MethodError: no method matching prepend!(::Array{Int64,1}, ::Int64)

In this example, a single element (7) is passed instead of a collection of elements. The prepend! function expects a collection as the second argument. Make sure to provide a collection (e.g., an array or vector) when using prepend!.

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: