Search code examples
enumeratenim-lang

Nim enumerate function like Python


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

Solution

  • 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.