What use for reversed()?
Jussi Piitulainen
jpiitula at ling.helsinki.fi
Mon Jun 1 02:11:14 EDT 2015
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
> <reversed object at 0x02B57F10>
>
> 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
<reversed object at 0xb70abc2c>
>>> list(listr)
['d', 'e', 'r', 'f']
>>> listr
<reversed object at 0xb70abc2c>
>>> 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.
More information about the Python-list
mailing list