How do I get the index whilst interating over a list with the For expression?


Is there a way to get the index number of the current item whilst iterating through a list with the For expression. Similar to how {iterator}.key works with for_each?:

Basically, I have n items in a list but don’t want to have to provide an attribute telling it what number in the list it is. In the below snippet, s.key doesn’t work, but hopefully it shows what I’m trying to achieve.

dynamic "subnet" {
for_each = [for s in each.value["subnets"]: {
  name   = format("%s%02d",, s.key)
  prefix = cidrsubnet(element(each.value["address_space"],0), s.newbits, s.key)

In PowerShell, I would do something like:

$list = @("Cat","Dog","Fish","Foo")

For ($i=0; $i -lt $list.Length; $i++)
    "$i $($list[$i])"

I’ve tried s, s.index, count

Any help, greatfully received.



Hi @arcotek-ltd,

If you provide two variable names after for then the first one will receive the key (or index) and the second will receive the value:

[for i, s in each.value["subnets"] : {
  name = format("%s%02d",, i)