# Any shortcut to 1:length(myVector)?

**URL:** <https://discourse.julialang.org/t/any-shortcut-to-1-length-myvector/52816>\
**Category:** General Usage\
**Created:** [January 4, 2021, 11:14am UTC](https://discourse.julialang.org/t/any-shortcut-to-1-length-myvector/52816 "2021-01-04T11:14:56Z")\
**Posts on this page:** 15\
**Page:** 2

<div class="post-metadata">

**Author:** ![jlapeyre](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jlapeyre/32/4514_2.png) [@jlapeyre](https://discourse.julialang.org/u/jlapeyre)\
**Post date:** [January 8, 2021, 1:50pm UTC](https://discourse.julialang.org/t/any-shortcut-to-1-length-myvector/52816/22 "2021-01-08T13:50:22Z")

</div>

If I were a beginner looking to this thread for a canonical way to do this, what would I take away? … `eachindex` ?

---

<div class="post-metadata">

**Author:** ![RGerzaguet](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rgerzaguet/32/45492_2.png) [@RGerzaguet](https://discourse.julialang.org/u/RGerzaguet)\
**Post date:** [January 8, 2021, 1:55pm UTC](https://discourse.julialang.org/t/any-shortcut-to-1-length-myvector/52816/23 "2021-01-08T13:55:47Z")

</div>

Probably ` 1:length(myVector)` 😃 even if `eachindex` is quite elegant.

On the same side, I often have to use several iterations to average my results, like

```julia
mcRuns = 10000;
for i = 1 : 1 : mcRuns 
   # Do some stupid stuff, 
   # without taking having to deal with i into account 
end

```

Is there a way to do this elegantly like

```julia
do mcRuns times 
   # Do some stupid stuff, more elegantly 
end

```

---

<div class="post-metadata">

**Author:** ![carstenbauer](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/carstenbauer/32/4981_2.png) [@carstenbauer](https://discourse.julialang.org/u/carstenbauer)\
**Post date:** [January 8, 2021, 2:46pm UTC](https://discourse.julialang.org/t/any-shortcut-to-1-length-myvector/52816/24 "2021-01-08T14:46:07Z")

</div>

IMHO, yes. `eachindex` is not just elegant but efficient. If you also need the values, go with `pairs`.

I you really want/need integers (even if more efficient indexing is possible) then I’d go with `1:length(v)` (or `enumerate` if I want the values as well).

And of course, if you only need the values you can simply write `for val in myVector`.

---

<div class="post-metadata">

**Author:** ![simeonschaub](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/simeonschaub/32/216566_2.png) [@simeonschaub](https://discourse.julialang.org/u/simeonschaub)\
**Post date:** [January 8, 2021, 3:04pm UTC](https://discourse.julialang.org/t/any-shortcut-to-1-length-myvector/52816/25 "2021-01-08T15:04:34Z")

</div>

> [@carstenbauer](#):
>
> I you really want/need integers (even if more efficient indexing is possible) then I’d go with `1:length(v)` (or `enumerate` if I want the values as well).

`1:length(v)` will fail for OffsetArrays. Use `LinearIndices(v)` instead if you want scalar indexing.

---

<div class="post-metadata">

**Author:** ![yurivish](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yurivish/32/307_2.png) [@yurivish](https://discourse.julialang.org/u/yurivish)\
**Post date:** [January 8, 2021, 3:04pm UTC](https://discourse.julialang.org/t/any-shortcut-to-1-length-myvector/52816/26 "2021-01-08T15:04:57Z")

</div>

> [@RGerzaguet](#):
>
> Probably ` 1:length(myVector)`

No, this advice is wrong. There are examples in this topic that show where this approach fails.

> [@RGerzaguet](#):
>
> Is there a way to do this elegantly like
> 
> ```julia
> do mcRuns times 
> # Do some stupid stuff, more elegantly 
> end
> 
> ```

You can say

```julia
for _ in 1:nRuns
    # ...
end

```

---

<div class="post-metadata">

**Author:** ![Henrique\_Becker](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/henrique_becker/32/15443_2.png) [@Henrique\_Becker](https://discourse.julialang.org/u/Henrique_Becker)\
**Post date:** [January 8, 2021, 6:07pm UTC](https://discourse.julialang.org/t/any-shortcut-to-1-length-myvector/52816/27 "2021-01-08T18:07:46Z")

</div>

Just go with:

`for value in container` – when you only care about iterating the values.  
`for index in eachindex(container)` – when you gonna just use the indexes, or the values are used very infrequently. EDIT: see below [1].  
`for (index, value) in pairs(container)` – when you gonna need both at each loop; or if you are using some more complex structure like `Dict`/trees and this may save some effort of hashing keys (or searching the tree) again.

[1] To complement: For simple code over `Vector`s there will probably no performance difference between `eachindex` + `container[index]` and `pairs`. If you gonna apply SSOT (Single Source of Truth) and you want to query the container every time instead of having bindings with cached values, then go for it. It may be better than using `pairs` in cases that, inside a single loop, the values may change inside the container and you always want to get the most recent values. But, theoretically, the performance of `pairs` will always be the same or better than `eachindex` + `container[index]` if both index and value are used.

---

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [January 8, 2021, 6:51pm UTC](https://discourse.julialang.org/t/any-shortcut-to-1-length-myvector/52816/28 "2021-01-08T18:51:42Z")

</div>

> [@Henrique\_Becker](#):
>
> `for index in eachindex(container)` – when you gonna just use the indexes, or the values are used very infrequently.

Do you think one should avoid, for performance reasons,

```julia
x = rand(1000)
y = rand(1000)
for i in eachindex(x)
   # do stuff with x[i]
   for j in eachindex(y)
      # do stuff with x[i] and y[j]
   end
end

```

in favor of

```julia
for vx in x
   # do stuff with vx
   for vy in y
      # do stuff with vx and vy
   end
end

```

I tested a small example here and, although the codes are not lowered to the same thing (I could imagine that they could be), and there are repeated `getindex(x,i)` calls in the first choice, I could not build an example where I could measure any performance difference at all.

Perhaps the advice is more _if the values are going to be used repeatedly many, many times_ instead of the _very infrequently_? (or, of course, if the structure is such that `getindex` for it is expensive for some reason).

Or maybe this is surprising advice to me because in what I do I only use vectors, matrices, etc, instead of `Dicts` or other data structures that require more sophisticated indexing?

---

<div class="post-metadata">

**Author:** ![Jeff\_Emanuel](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeff_emanuel/32/15440_2.png) [@Jeff\_Emanuel](https://discourse.julialang.org/u/Jeff_Emanuel)\
**Post date:** [January 8, 2021, 7:17pm UTC](https://discourse.julialang.org/t/any-shortcut-to-1-length-myvector/52816/29 "2021-01-08T19:17:06Z")

</div>

Especially since you see negligble performance difference, if you only use i for x[i] and j for y[j], then I’d greatly prefer the second example for simplicity and clarity.

---

<div class="post-metadata">

**Author:** ![Henrique\_Becker](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/henrique_becker/32/15443_2.png) [@Henrique\_Becker](https://discourse.julialang.org/u/Henrique_Becker)\
**Post date:** [January 8, 2021, 7:19pm UTC](https://discourse.julialang.org/t/any-shortcut-to-1-length-myvector/52816/30 "2021-01-08T19:19:08Z")

</div>

If your `container` is a `Vector` and it is indexed a single time, then there will probably be no difference in performance. Sometimes even if it is indexed multiple times (if the compiler can prove it does not change).

I would go with `pairs` in this case anyway because I believe the code may change and `eachindex` may become a worse decision, but I do not see the opposite happening (i.e., I do not see `eachindex` becoming a better decision than `pairs` in a code that use both index and value). But if the code is guaranteed to not change too much (i.e., will keep using `Vector`s and not making so many accesses) then the decision ends up being mostly stylistic. I would only recommend `eachindex` if you really is **semantically** iterating positions and may change the value in the indexed position inside the loop before accessing it again and therefore using `pairs` can lead to a subtle bug of using the old value stored in `value` instead of the new in the indexed position.

EDIT: updated my first answer to address some cases I thought only after after this question.

---

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [January 8, 2021, 7:31pm UTC](https://discourse.julialang.org/t/any-shortcut-to-1-length-myvector/52816/31 "2021-01-08T19:31:17Z")

</div>

Just for completeness, at the end there is no alternative for a loop like this, is there? (except for `firstindex` and `lastindex`, which would support offset arrays)?

```julia
N = length(x)
for i in 1:N-1
   for j in i+1:N
      # do stuff with x[i] and x[j]
   end
end

```

---

<div class="post-metadata">

**Author:** ![yurivish](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yurivish/32/307_2.png) [@yurivish](https://discourse.julialang.org/u/yurivish)\
**Post date:** [January 8, 2021, 7:38pm UTC](https://discourse.julialang.org/t/any-shortcut-to-1-length-myvector/52816/32 "2021-01-08T19:38:59Z")

</div>

```julia
N = length(x)
I = LinearIndices(x)
for i in I[1:N-1]
   for j in I[i+1:N]
      # do stuff with x[i] and x[j]
   end
end

```

---

<div class="post-metadata">

**Author:** ![dlfivefifty](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dlfivefifty/32/1959_2.png) [@dlfivefifty](https://discourse.julialang.org/u/dlfivefifty)\
**Post date:** [January 11, 2021, 10:37pm UTC](https://discourse.julialang.org/t/any-shortcut-to-1-length-myvector/52816/33 "2021-01-11T22:37:17Z")

</div>

I really do think `axes` is the “canonical” way to do these things, e.g. you could do:

```julia
for i in axes(x,1)[begin:end-1]
   for j in i+1:axes(x,1)[end]
      # do stuff with x[i] and x[j]
   end
end

```

and it will work with offset arrays.

---

<div class="post-metadata">

**Author:** ![yurivish](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yurivish/32/307_2.png) [@yurivish](https://discourse.julialang.org/u/yurivish)\
**Post date:** [January 12, 2021, 12:03am UTC](https://discourse.julialang.org/t/any-shortcut-to-1-length-myvector/52816/34 "2021-01-12T00:03:25Z")

</div>

I think that approach won’t work with a `Matrix`, since you are iterating only over the first axis:

```julia
julia> x = [1 2; 3 4]
2×2 Array{Int64,2}:
 1 2
 3 4

julia> for i in axes(x,1)[begin:end-1]
          for j in i+1:axes(x,1)[end]
             @show x[i] x[j]
          end
       end
x[i] = 1
x[j] = 3
```

---

<div class="post-metadata">

**Author:** ![dlfivefifty](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dlfivefifty/32/1959_2.png) [@dlfivefifty](https://discourse.julialang.org/u/dlfivefifty)\
**Post date:** [January 12, 2021, 10:13am UTC](https://discourse.julialang.org/t/any-shortcut-to-1-length-myvector/52816/35 "2021-01-12T10:13:58Z")

</div>

Why would a `Matrix` be named `myVector`??

---

<div class="post-metadata">

**Author:** ![yurivish](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yurivish/32/307_2.png) [@yurivish](https://discourse.julialang.org/u/yurivish)\
**Post date:** [January 12, 2021, 2:35pm UTC](https://discourse.julialang.org/t/any-shortcut-to-1-length-myvector/52816/36 "2021-01-12T14:35:54Z")

</div>

Hopefully it wouldn’t be! 😄

[Previous page](https://discourse.julialang.org/t/any-shortcut-to-1-length-myvector/52816.md?page=1)
