0

I am creating an iterator using the iter function and iterating several steps using the iterator.

I then want to continue iterating from the same place with a different iterator without affecting the original iterator object.

example:

consider the iterator object org_iter:

>>> a = [1,2,3,4,5]
>>> org_iter = iter(a)

iterating over it:

>>> next(org_iter)
1

using iter again gives the same instance of the iterator instead of a different one from the same location:

>>> new_iter = iter(org_iter)
>>> next(new_iter)  # continuing 
2
>>> next(org_iter)  # "org_iter is new_iter"
3

EDIT because of comment: using itertools.tee doesn't work either:

>>> new_iter = itertools.tee(org_iter)
>>> next(new_iter[0])
2
>>> next(org_iter)
3

the same functionality could be achieved by using different variables to hold the index numbers and +=1ing them.

or with the enumerate function and nested for loops.

but i am specifically asking about using an iterator object directly.

moshevi
  • 4,999
  • 5
  • 33
  • 50
  • You are using [tee](https://docs.python.org/3/library/itertools.html#itertools.tee) incorrectly. You would do `it1, it2=itertools.tee(iter(a))` and it then works as you expect. You cannot use the original iterator once you have used `tee`. – dawg Aug 05 '18 at 14:38
  • this doesn't allow me to continue from the same place as the original iterator, i will have to create both of them at the beginning and iterate over both of them and this is not my question. i am creating iterators dynamically i can't know how many i will need. – moshevi Aug 05 '18 at 14:53
  • Again: It works as expected so long as you do not use the original. Try: `oi=iter(a)` couple of nexts then do `i1,i2=itertools.tee(iter(oi))` and don't use `oi` at that point. `i1` and `i2` are now where `oi` was and can be used independently from there. – dawg Aug 05 '18 at 15:14
  • If it is not clear, you can also reuse the original name: `oi,new_i=itertools.tee(iter(oi))` so it is functionally the same as keeping the original. – dawg Aug 05 '18 at 16:18

1 Answers1

1

One way I can think of without using any external modules would be by doing:

>>> a = [1, 2, 3, 4, 5]
>>> org_iter = iter(a)
>>> id(org_iter)
58713584
>>> new_iter = iter(list(org_iter))
>>> id(new_iter)
58299600
BPL
  • 9,632
  • 9
  • 59
  • 117