Search code examples
pythonfor-looppython-itertools

Calling indices in an expression while iterating over a variable number of indices (Python)


I want to iterate over a variable number of indices given by the length of a list, using the values on the list as the ranges. Further, I want to call the indices in my expression.

For example, if I have a list [2,4,5], I would want something like:

import itertools

for i0, i1, i2 in itertools.product(range(2),range(4),range(5)):
    otherlist[i0]**i0 + otherlist[i2]**i2

The closest I can get is

for [i for i in range(len(mylist))] in itertools.product(*[range(i) for i in mylist]):
    

But I don't know how to call the indices from here.


Solution

  • You were so close already. When you use a for statement, I find it best to keep the target list simple and access components of the target list in the for-loop; in this code, the tuples generated by product().

    import itertools
    
    mylist = [2,4,5]
    otherlist = list(range(5))
    
    for t in itertools.product(*[range(i) for i in mylist]):
        print(otherlist[t[0]]**t[0] + otherlist[t[2]]**t[2])
    # 2
    # 2
    # 5
    # 28
    # 257
    # ...