Jellybeard Jellybeard - 10 months ago 48
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


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

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

x = 2

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

for x in range (5):

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 Source
for x in range (5):

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):