iterator - Why does Python's itertools.cycle need to create a copy of the iterable? -


the documentation python's itertools.cycle() gives pseudo-code implementation as:

def cycle(iterable):     # cycle('abcd') --> b c d b c d b c d ...     saved = []     element in iterable:         yield element         saved.append(element)     while saved:         element in saved:               yield element 

below, states: "note, member of toolkit may require significant auxiliary storage (depending on length of iterable)."

i going down path, except did this, not require creating copy of iterable:

def loop(iterable):     = iterable.__iter__()      while true:         try:             yield it.next()         except stopiteration:             = iterable.__iter__()             yield it.next()  x = {1, 2, 3}  hard_limit = 6 in loop(x):     if hard_limit <= 0:         break      print     hard_limit -= 1 

prints:

1 2 3 1 2 3 

yes, realize implementation wouldn't work str's, made to. i'm more curious why creates copy. have feeling has garbage collection, i'm not studied in area of python.

thanks!

iterables can iterated on once.

you create new iterable in loop instead. cycle cannot that, has work whatever passed in. cycle cannot recreate iterable. forced store elements original iterator produces.

if pass in following generator instead, loop() fails:

def finite_generator(source=[3, 2, 1]):     while source:         yield source.pop() 

now loop() produces:

>>> hard_limit = 6 >>> in loop(finite_generator()): ...     if hard_limit <= 0: ...         break ...     print ...     hard_limit -= 1 ...  1 2 3 

your code work sequences, using cycle() overkill; don't need storage burden of cycle() in case. simplify down to:

def loop_sequence(seq):     while true:         elem in seq:             yield elem 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -