6

Learning Nim and I like it resemblence of Python (but fast). In Python I can do this:

item_index = [(idx, itm) for idx, itm in enumerate(row)]

Im looking for a way to enumerate a Nim sequence so I would write this:

item_index = lc[(idx, itm) | (idx, itm <- enumerate(row))]

Does this functionality exist? I'm sure you could create it, maybe with a proc, template or macro it but I'm still very new, and these seem hard to create myself still. Here is my attempt:

iterator enumerate[T](s: seq[T]): (int, T) =
    var i = 0
    while i < len(s):
        yield (i, s[i])
        i += 1
Peheje
  • 12,542
  • 1
  • 21
  • 30

1 Answers1

13

I'm a newbie with nim, and I'm not really sure what you want, but... If you use two variables in a for statement, you will get the index and the value:

for x, y in [11,22,33]:
  echo x, " ", y

Gives:

0 11
1 22
2 33

HTH.

aMike
  • 852
  • 5
  • 14
  • 9
    Some background why this works: When Nim's sees a for loop with two loop variables, it tries to call `pairs` on the given expression. The `pairs` operator is defined for `openarray` in [system.nim](https://nim-lang.org/docs/system.html#pairs.i,openArray[T]) and it does [exactly](https://github.com/nim-lang/Nim/blob/9ca56863982fd623739e36adbc1455a2d5c5c8e7/lib/system.nim#L2142) what `enumerate` does. – bluenote10 Jan 06 '18 at 10:43
  • 2
    Please note that this doesn't work for all iterables. For example, if you try to do this with `start .. end` or with `countup(start, end, step)` you will get a `wrong number of variables` error. – Arthur Khazbs Aug 06 '20 at 07:34
  • @ArthurKhazbs why would you do that?, OP is trying to iterate an array. – shuji Oct 09 '20 at 21:18