# Use of getindex.(L,1) in a for loop

**URL:** <https://discourse.julialang.org/t/use-of-getindex-l-1-in-a-for-loop/44940>\
**Category:** New to Julia\
**Created:** [August 14, 2020, 3:51pm UTC](https://discourse.julialang.org/t/use-of-getindex-l-1-in-a-for-loop/44940 "2020-08-14T15:51:28Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![juliamatt](https://avatars.discourse-cdn.com/v4/letter/j/eb8c5e/32.png) [@juliamatt](https://discourse.julialang.org/u/juliamatt)\
**Post date:** [August 14, 2020, 3:51pm UTC](https://discourse.julialang.org/t/use-of-getindex-l-1-in-a-for-loop/44940/1 "2020-08-14T15:51:28Z")

</div>

I am converting some old Julia 0.5 code into Matlab. I know broadcasting uses the dot notation but I don’t understand why you would want to use:

> L = getindex.(L,1)

inside a for or while loop in Julia code. At the command prompt you get the same as the variable name as output so in Matlab I am just ignoring the getindex part so:

> g = getindex.(function(blah),1)

I just say is:

> g = function(blah)

which seems to work fine but I must be missing the point of what the original code was trying to do.  
thanks,

---

<div class="post-metadata">

**Author:** ![tomerarnon](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tomerarnon/32/3170_2.png) [@tomerarnon](https://discourse.julialang.org/u/tomerarnon)\
**Post date:** [August 14, 2020, 3:55pm UTC](https://discourse.julialang.org/t/use-of-getindex-l-1-in-a-for-loop/44940/2 "2020-08-14T15:55:29Z")

</div>

`getindex` does what square brackets does.

```julia
julia> a = rand(2,2)
2×2 Array{Float64,2}:
 0.573604 0.332509
 0.571927 0.137868

julia> a[1]
0.5736038727235953

julia> getindex(a, 1)
0.5736038727235953

julia> a[1, :]
2-element Array{Float64,1}:
 0.5736038727235953
 0.332508603490159 

julia> getindex(a, 1, :)
2-element Array{Float64,1}:
 0.5736038727235953
 0.332508603490159 

```

`getindex.(L, 1)` is broadcasting the getindex operation on each element of `L`. In this case, assuming the elements of `L` don’t have custom indexing, it’s the same as doing `first.(L)`. Note that L = `getindex.(L, 1)` is very probably not type stable.

---

<div class="post-metadata">

**Author:** ![juliamatt](https://avatars.discourse-cdn.com/v4/letter/j/eb8c5e/32.png) [@juliamatt](https://discourse.julialang.org/u/juliamatt)\
**Post date:** [August 14, 2020, 4:18pm UTC](https://discourse.julialang.org/t/use-of-getindex-l-1-in-a-for-loop/44940/3 "2020-08-14T16:18:31Z")

</div>

I think it must have been to remove cells or square brackets around values within an array. So I guess that is why you said it is not type stable. I found you can remove square brackets in an array. I realise this doesn’t make much sense.

eg:

> L = [1,2,[3]]  
> then use:

> L = getindex.(L,1)

recovers the array as floating point numbers.

I might be wrong in assuming that was why it was used. 🙂 🙂
