0

Part of my code involves accessing the pre-defined variables in a for loop. However, trying to access the already existing variables in a for loop doesn't seem to work:

import itertools
def f(x):
    x1, x2 = itertools.tee(x)
    print(list(x1), list(x2))
    for i in range(1):
        print(list(x1), list(x2))

f(iter([1,2]))

Is there any way to resolve this?

  • You know that `range(1)` just contains a single value, `0`, right? You could replace it with `i = 0` and get rid of the loop if that's really what you want. – Tom Karzes May 01 '20 at 08:52

1 Answers1

0

the problem as x1 and x2 are iterable and when you are print(list(x1), list(x2)) the iterable are gone no have longer next so you should remove this line

import itertools

def f(x): 
    x1, x2 = itertools.tee(x) 
    #print(list(x1), list(x2)) 
    print(type(x1), type(x2)) 
    for i in range(1): 
        print(i) 
        print(list(x1), list(x2)) 

f([1,2])                           

output

<class 'itertools._tee'> <class 'itertools._tee'>
0
[1, 2] [1, 2]
Beny Gj
  • 607
  • 4
  • 16