Tee function from itertools library

Both list and islice objects are iterable, but why is this difference the result.

r = [1, 2, 3, 4]               
i1, i2 = tee(r)
print [e for e in r if e < 3]
print [e for e in i2]
#[1, 2]
#[1, 2, 3, 4]


r = islice(count(), 1, 5)          
i1, i2 = tee(r)
print [e for e in r if e < 3]
print [e for e in i2]
#[1, 2]
#[]
+5
source share
2 answers

The problem here is that it tee()should consume values ​​from the original iterator, if you start using them from the original iterator, it will not be able to function normally. In your example list, iteration just starts again. In the generator example, it is exhausted and no more values ​​are created.

This is well documented:

After tee () has done the split, the original iterable should not be used anywhere; otherwise, iterability could be improved without notifications of shadow objects.

Source

, :

>>> from itertools import islice, count
>>> a = list(range(5))
>>> b = islice(count(), 0, 5)
>>> a
[0, 1, 2, 3, 4]
>>> b
<itertools.islice object at 0x7fabc95d0fc8>
>>> for item in a:
...     print(item)
... 
0
1
2
3
4
>>> for item in a:
...     print(item)
... 
0
1
2
3
4
>>> for item in b:
...     print(item)
... 
0
1
2
3
4
>>> for item in b:
...     print(item)
... 
>>> 
+14

r i1.

0

All Articles