What use for reversed()?

Denis McMahon denismfmcmahon at gmail.com
Sun May 31 15:58:19 EDT 2015


On Sun, 31 May 2015 12:40:19 -0700, fl wrote:

> Hi,
> 
> I have a string b='1234'. I run: br=reversed(b)
> 
> I hope that I can print out '4321' by:
> 
> for br in b
> 
> but it complains:
> SyntaxError: invalid syntax
> 
> 
> My questions:
> 1. What use for reversed(). I do not find an example on web.
> 
> 2. If reversed() is wrong the my purpose, what method can do it? i.e.
> '4321'
> out.

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

-- 
Denis McMahon, denismfmcmahon at gmail.com



More information about the Python-list mailing list