4

I wish to iterate over a list_iterator twice. When I currently try to do this, the iterator has nothing to iterate over the second time. Can I reset it?

l = iter(["1","2","3","4"])

for i in l:
   print(i)

for i in l:
   print(i)

A list_iter object is being passed to the function in which I wish to iterate twice in. Is it bad practive to pass around list_iterator objects?

Baz
  • 12,713
  • 38
  • 145
  • 268
  • 1
    It's better to pass the list itself, no need to create an iterator. – Ashwini Chaudhary Jan 22 '14 at 13:08
  • 1
    Iterators are "use and throw" type objects – thefourtheye Jan 22 '14 at 13:10
  • "Is it bad practive to pass around list_iterator objects?" - my experience is that it can cause some confusion to pass around things that can only be iterated once (even generator and file objects it's not necessarily obvious to the recipient what they're getting). Functions need to document whether their inputs need to be iterable multiple times, and whether their outputs can be iterated multiple times. It's expected, for example any function with a `yield` returns something that can only be iterated once. You just have to make sure you know when it has happened. – Steve Jessop Jan 22 '14 at 13:36

1 Answers1

3

You could always use itertools.tee to get copies of the iterable.

Ala

l = iter(["1","2","3","4"])
# Don't use original....
original, new = tee(l)
Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91