0

other questions have already clarified, that in python3 filter returns an iterator. to print it, one may use the list function:

odds = filter(lambda x: x>2,[1,2,3,1.1,1.2,1.3,4])
print(list(odds))

this prints correctly:

[3, 4]

however, the execution of list 'consumes' the iterator produced by list. so, if I call again:

print(list(odds))

this prints an empty string. most importantly, if I use the list function to see the iterator, then I cannot use it later in my script (e.g. as an iterator), because it has been consumed/emptied/iterated. is there a way to see the iterator without consuming it or is it like the uncertainty principle in quantum mechanics, that if I observe an iterator I also modify it? I think the answer is no, but I thought it would be useful for other stackoverflowers to know this issue.

fabiob
  • 273
  • 4
  • 14
  • Just save it in a list – Olivier Melançon Aug 28 '19 at 14:21
  • 1
    Also possibly [How to look ahead one element (peek) in a Python generator?](https://stackoverflow.com/questions/2425270/how-to-look-ahead-one-element-peek-in-a-python-generator). – glibdud Aug 28 '19 at 14:22
  • @glibdud Using tee, as suggested in the duplicate, is useless when traversing the whole iterator. It's more efficient to cast it to a list then because tee simply saves it as a list and adds some overhead – Olivier Melançon Aug 28 '19 at 14:31
  • 2
    @OlivierMelançon A lot of things are discussed in the duplicate, including the idea of using a list or simply regenerating the iterator. There isn't anything particularly new about this question. – glibdud Aug 28 '19 at 14:42
  • @glibdud You are right, I read too fast – Olivier Melançon Aug 28 '19 at 15:10
  • I think the answer to my question is then 'no'. Creating a list, using tee, or producing a function that outputs the iterator (see below) are workarounds, each has pros and cons (use of memory vs. computing costs). True, these are explained in the proposed duplicate. But I believe my question is formulated in a different way and could be still useful. Do you still suggest to delete it because it is a duplicate? – fabiob Aug 28 '19 at 15:17
  • 1
    @fabiob No, duplicate are not necessarly bad. They are way to reword an already existing question. So please do not delete it. – Olivier Melançon Aug 28 '19 at 16:02

1 Answers1

0

You could use a lambda that returns a new iterator:

odds = lambda: filter(lambda x: x>2,[1,2,3,1.1,1.2,1.3,4])
print(list(odds())) # [3, 4]
print(list(odds())) # [3, 4]