itertools cycle() docs question

Chris Angelico rosuav at gmail.com
Wed Aug 21 16:00:41 EDT 2019


On Thu, Aug 22, 2019 at 5:56 AM Tobiah <toby at tobiah.org> wrote:
>
> On 8/21/19 11:38 AM, Rob Gaddi wrote:
> > On 8/21/19 11:27 AM, Tobiah wrote:
> >> In the docs for itertools.cycle() there is a bit of equivalent code
> >> given:
> >>
> >> def cycle(iterable): # cycle('ABCD') --> A B C D A B C D A B C D
> >> ... saved = [] for element in iterable: yield element
> >> saved.append(element) while saved: for element in saved: yield
> >> element
> >>
> >>
> >> Is that really how it works?  Why make the copy of the elements?
> >> This seems to be equivalent:
> >>
> >>
> >> def cycle(iterable): while iterable: for thing in iterable: yield
> >> thing
> >
> > You assume that the initial iterable is reusable.  If its not, the
> > only way you can go back to the beginning is to have kept track of it
> > yourself.
> >
>
> I see.  What is an example of an iterable that is not reusable?

Just call iter() on pretty much any iterable, and you'll get back
something that's not reusable.

ChrisA



More information about the Python-list mailing list