# Why does indexed assignment return the assigned value instead of the container?

**URL:** <https://discourse.julialang.org/t/why-does-indexed-assignment-return-the-assigned-value-instead-of-the-container/71399>\
**Category:** Internals & Design\
**Tags:** question\
**Created:** [November 12, 2021, 6:39pm UTC](https://discourse.julialang.org/t/why-does-indexed-assignment-return-the-assigned-value-instead-of-the-container/71399 "2021-11-12T18:39:55Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![MatthijsBlom](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/matthijsblom/32/30754_2.png) [@MatthijsBlom](https://discourse.julialang.org/u/MatthijsBlom)\
**Post date:** [November 12, 2021, 6:39pm UTC](https://discourse.julialang.org/t/why-does-indexed-assignment-return-the-assigned-value-instead-of-the-container/71399/1 "2021-11-12T18:39:55Z")

</div>

Witness

```julia
x = ['a']
setindex!(x, 'b', 1) # ['b']
x[1] = 'c' # 'c'

```

This behaviour is documented:

> The syntax `a[i,j,...] = x` is converted by the compiler to `(setindex!(a, x, i, j, ...); x)`.

(The documentation seems silent on the return value of `setindex!`.)

I have two questions:

- **main question:** Why does indexed assignment return the assigned value?
- **side question:** Why does `setindex!` return the container instead?

---

<div class="post-metadata">

**Author:** ![fredrikekre](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fredrikekre/32/1688_2.png) [@fredrikekre](https://discourse.julialang.org/u/fredrikekre)\
**Post date:** [November 12, 2021, 6:47pm UTC](https://discourse.julialang.org/t/why-does-indexed-assignment-return-the-assigned-value-instead-of-the-container/71399/2 "2021-11-12T18:47:15Z")

</div>

> [@MatthijsBlom](#):
>
> Why does indexed assignment return the assigned value?

It is convenient for multiple assignments, for example:

```julia
julia> x = [1, 2, 3]; y = [4, 5, 6];

julia> x[2] = y[2] = 42;

julia> x
3-element Vector{Int64}:
  1
 42
  3

julia> y
3-element Vector{Int64}:
  4
 42
  6

```

> [@MatthijsBlom](#):
>
> Why does `setindex!` return the container instead?

It is convention that `!`-functions return the mutated container. This is also convenient for nesting, example (although not with `setindex!` which is rarely used directly):

```julia
julia> x = [1, 2, 3];

julia> push!(empty!(x), 42); # empty! returns x

julia> x
1-element Vector{Int64}:
 42

```
