Suppose I have the following function:
def print_twice(x):
for i in x: print(i)
for i in x: print(i)
When I run:
print_twice([1,2,3])
or:
print_twice((1,2,3))
I get the expected result: the numbers 1,2,3 are printed twice.
But when I run:
print_twice(zip([1,2,3],[4,5,6]))
the pairs (1,4),(2,5),(3,6) are printed only once. Probably, this is because the zip
returns a generator that terminates after one pass.
How can I modify the function print_twice
such that it will correctly handle all inputs?
I could insert a line at the beginning of the function: x = list(x)
. But this might be inefficient in case x is already a list, a tuple, a range, or any other iterator that can be iterated more than once. Is there a more efficient solution?