insert!
insert!(collection, index, item)
Insert an item into collection at the given index.
index is the index of item in the resulting collection.
julia> insert!([6, 5, 4, 2, 1], 4, 3)
6-element Array{Int64,1}:
6
5
4
3
2
1Examples
julia> insert!([6, 5, 4, 2, 1], 4, 3)
6-element Array{Int64,1}:
6
5
4
3
2
1
julia> foo = [4,2,1];
julia> insert!(foo, 2, 3);
julia> foo
4-element Array{Int64,1}:
4
3
2
1
-
Insert an element into an array:
julia> arr = [10, 20, 30, 40, 50]; julia> insert!(arr, 2, 15) 6-element Array{Int64,1}: 10 15 20 30 40 50This example inserts the element
15at index2in the arrayarr. -
Modify a vector of strings:
julia> words = ["apple", "banana", "grape"]; julia> insert!(words, 2, "orange") 4-element Array{String,1}: "apple" "orange" "banana" "grape"It inserts the string
"orange"at index2in the vector of strings. - Handle edge cases when inserting at the end:
julia> numbers = [1, 2, 3]; julia> insert!(numbers, 4, 4) 4-element Array{Int64,1}: 1 2 3 4It correctly handles the case where the element is inserted at the end of the collection.
Common mistake example:
julia> arr = [5, 10, 15, 20];
julia> insert!(arr, 6, 25)
ERROR: BoundsError: attempt to access 4-element Array{Int64,1} at index [6]
In this example, the index provided is out of bounds for the array. It's important to ensure that the index is within the valid range of the collection to avoid such errors. Always check that the index is a valid position in the collection before using insert!.
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.