splice!(collection, index, replacement = ?)

splice!(collection, index, [replacement]) -> item

Remove the item at the given index, and return the removed item. Subsequent items are shifted down to fill the resulting gap. If specified, replacement values from an ordered collection will be spliced in place of the removed item.

julia> A = [6, 5, 4, 3, 2, 1]; splice!(A, 5)
2

julia> A
5-element Array{Int64,1}:
 6
 5
 4
 3
 1

julia> splice!(A, 5, -1)
1

julia> A
5-element Array{Int64,1}:
  6
  5
  4
  3
 -1

julia> splice!(A, 1, [-1, -2, -3])
6

julia> A
7-element Array{Int64,1}:
 -1
 -2
 -3
  5
  4
  3
 -1

To insert replacement before an index n without removing any items, use splice!(collection, n:n-1, replacement).

Examples

julia> arr = [3,4,5]
       splice!(arr,2)
4
julia> foo = [6, 5, 4, 3, 2, 1]; splice!(foo, 5)
2

julia> foo
5-element Array{Int64,1}:
 6
 5
 4
 3
 1

julia> splice!(foo, 5, -1)
1

julia> foo
5-element Array{Int64,1}:
  6
  5
  4
  3
 -1

julia> splice!(foo, 1, [-1, -2, -3])
6

julia> foo
7-element Array{Int64,1}:
 -1
 -2
 -3
  5
  4
  3
 -1

julia> splice!(foo, 4:3, 2)                 # insert 2 before index 4
0-element Array{Int64,1}

julia> foo
8-element Array{Int64,1}:
 -1
 -2
 -3
  2
  5
  4
  3
 -1
  1. Remove and replace elements in an array:

    julia> arr = [1, 2, 3, 4, 5];
    julia> splice!(arr, 2:3, [10, 20, 30])
    5-element Array{Int64,1}:
    1
    10
    20
    30
    4

    This example removes the elements at index 2 and 3 from the array arr and replaces them with [10, 20, 30].

  2. Insert elements at a specific index in a vector:

    julia> vec = ['a', 'b', 'c', 'd'];
    julia> splice!(vec, 4:3, ['x', 'y'])
    5-element Array{Char,1}:
    'a'
    'b'
    'x'
    'y'
    'c'

    It removes the elements at index 4 and inserts ['x', 'y'] in their place.

  3. Remove elements without replacement:
    julia> numbers = [1, 2, 3, 4, 5];
    julia> splice!(numbers, 1:2)
    2-element Array{Int64,1}:
    1
    2

    This example removes elements at index 1 and 2 from the numbers array without replacing them.

Common mistake example:

julia> arr = [1, 2, 3, 4, 5];
julia> splice!(arr, 6:7, [10, 20])
ERROR: BoundsError: attempt to access 5-element Array{Int64,1} at index [6:7]

In this case, the provided range exceeds the valid indices of the collection arr. Ensure that the range is within the bounds of the collection before using splice!.

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: