Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!1.eu.feeder.erje.net!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Jussi Piitulainen Newsgroups: comp.lang.python Subject: Re: What use for reversed()? Date: Mon, 01 Jun 2015 09:11:14 +0300 Organization: A noiseless patient Spider Lines: 72 Message-ID: References: <514c05fc-dded-4278-ac86-3e8e3cd0e851@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx02.eternal-september.org; posting-host="305c68510616a2e7ac08bcd2ff1598bd"; logging-data="9672"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19lARm+eARV9qf4qRp/OKOzFXHMTJJdL0I=" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:mA2siENqQH928K5fwyIqq2LLhBo= sha1:9U3i15jW7qsQNVvK4oui369W0xw= Xref: csiph.com comp.lang.python:91622 fl writes: > On Sunday, May 31, 2015 at 12:59:47 PM UTC-7, Denis McMahon wrote: >> On Sun, 31 May 2015 12:40:19 -0700, fl wrote: >> reversed returns an iterator, not a list, so it returns the reversed >> list of elements one at a time. You can use list() or create a list >> from reversed and then join the result: [snip] > I follow your reply with these trials: > > >>>>list_r=(reversed("fred")) > >>> list(list_r) > ['d', 'e', 'r', 'f'] > >>> list_r > > > I have searched about list, but I still don't know what list_r is. It's an object that will produce elements on demand. The doc string (Python 2.7.6) calls it an iterator: "reversed(sequence) -> reverse iterator over values of the sequence". Such objects "have state". Try to consume it *twice*, it'll be empty the second time: >>> listr = reversed('fred') >>> listr >>> list(listr) ['d', 'e', 'r', 'f'] >>> listr >>> list(listr) [] You can ask for the next element of the iterator: >>> listr = reversed('fred') >>> next(listr) 'd' >>> list(listr) ['e', 'r', 'f'] > What else can it be used besides list(list_r)? Piecemeal walking using next(list_r), as the source of elements in a for loop, as a sequence argument to many functions that only need to walk it once (but they will consume it!). The suggested ''.join(reversed('fred')) is an example. > I want to show list_r content. This is possibly an illegal question. You could do this: >>> from __future__ import print_function >>> listr = reversed('fred') >>> for c in listr: print(c, end = '') ... else: print() ... derf But then listr won't have that content, or any content, any more. The act of looking inside has changed listr :) Such objects are quite powerful when used properly. The sequence they produce can be larger than available memory because it need only exist one element at a time.