What use for reversed()?

Ian Kelly ian.g.kelly at gmail.com
Sun May 31 20:06:13 EDT 2015


On Sun, May 31, 2015 at 1:58 PM, Denis McMahon <denismfmcmahon at gmail.com> 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:
>
> $ python
> Python 2.7.3 (default, Dec 18 2014, 19:10:20)
> [GCC 4.6.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> "".join(list(reversed("fred")))
> 'derf'
>>>> "".join([x for x in reversed("fred")])
> 'derf'
>
> So reversed can do it, but needs a little help

The str.join method will happily accept an iterator, so the
intermediate list construction in those examples is unnecessary.



More information about the Python-list mailing list