Jellybeard Jellybeard - 18 days ago 8
Python Question

Why does explicit definition of a variable work to call a function but an iterator will not?

This python script returns a value of 90.0:

import itertools

a=[12,345,1423,65,234]
b=[234,12,34,1,1,1]
c=[1,2,3,4]

def TestFunction (a, b, c):
result = a + b/c
return result

Params=itertools.product(a, b, c)

x = 2
print(TestFunction(*list(Params)[x]))


However, I would like to evaluate my function for a range of x as:

for x in range (5):
print(TestFunction(*list(Params)[x]))


I expected this to return a sequence of values: 246.0, 129.0, 90.0, 70.5, 14.0; however, i get "IndexError: list index out of range." Why does the function evaluate when x is defined explicitly but not when it is an iterator?

Answer
for x in range (5):
    print(TestFunction(*list(Params)[x]))

Params is an iterator. The first time through the loop, you consume it entirely by converting it to a list. Therefore on the second iteration there's nothing in it and converting it to a list yields [], the empty list, and trying get index 1 of that won't work.

Instead, convert the iterator to a list outside the loop.

params = list(Params)
for x in range(5):
    print(TestFunction(*params[x]))