setindex!(A::AbstractArray,X,inds...)

setindex!(A, X, inds...)

Store values from array X within some subset of A as specified by inds.

Examples

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

julia> bar = zeros(2, 2);           # 2x2 array of zeros
julia> setindex!(bar, 42, 2, 1)
2x2 Array{Float64,2}:
0.0   0.0
42.0  0.0

In the Julia programming language, the function setindex!(collection, value, key...)

Store the given value at the given key or index within a collection. The syntax a[i,j,...] = x is converted by the compiler to (setindex!(a, x, i, j, ...); x).

julia> arr = [1, 2, 3, 4, 5];
julia> setindex!(arr, 10, 3)
5-element Array{Int64,1}:
  1
  2
 10
  4
  5
  1. Set value at a specific index:

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

    This example sets the value 10 at index 3 in the array arr.

  2. Modify a dictionary:

    julia> dict = Dict("apple" => 10, "banana" => 20, "orange" => 30);
    julia> setindex!(dict, 25, "banana")
    Dict{String,Int64} with 3 entries:
    "apple"  => 10
    "banana" => 25
    "orange" => 30

    It sets the value 25 for the key "banana" in the dictionary dict.

  3. Set value at multiple indices:
    julia> arr = [1, 2, 3, 4, 5];
    julia> setindex!(arr, 0, 2, 4)
    5-element Array{Int64,1}:
    1
    0
    3
    0
    5

    This example sets the value 0 at indices 2 and 4 in the array arr.

Common mistake example:

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

In this example, the index provided is out of bounds for the array. Ensure that the index is within the valid range of the collection to avoid such errors.

See Also

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: