← retour aux snippets

itertools.tee: dupliquer un iterator (avec précautions)

Créer des copies indépendantes d'un iterator tout en gérant le buffer.

python itertools #itertools#tee#iterators

objectif

Créer des copies indépendantes d’un iterator tout en gérant le buffer.

code minimal

from itertools import tee
it1, it2 = tee(iter([1,2,3]))
print(next(it1) == 1 and list(it2) == [1,2,3])  # attendu: True

utilisation

from itertools import tee
a, b = tee(range(5))
list(a)  # consomme a
print(sum(b) == sum(range(5)))  # b reste intact

variante(s) utile(s)

from itertools import tee
x,y = tee([1,2])
print(list(x) == [1,2] and list(y) == [1,2])

notes

  • tee met en buffer les éléments consommés par une copie et pas l’autre.
  • Évitez sur des flux très gros non bornés: préférez list() si mémoire ok.