Home python Reversed () function in python

Reversed () function in python

Author

Date

Category

If you write like this.

s = 'abc'
Print (REVERSED (S))

In response, I get – Reversed Object AT 0x003248F0.
Together with Join, it works as it should.

s = 'abc'
Print (''. Join (Reversed (S)))

In response – CBA.
So the question is – why the function is directly with the rows, does not work?


Answer 1, Authority 100%

Reversed () works with Arbitrary sequences or objects with __ REVERSED __ () method and always returns iterator , by order which you can get the elements of the input sequence in the reverse order.

The string is a sequence and then reversed () can work with it. To get the reverse line at once, you can use the expression s [:: - 1] :

& gt; & gt; & gt; 'ABC' [:: - 1]
'CBA'

Good question, why the function is Reversed () does not return the string if it gives the line to the line. For example, Filter () Function on Python 2 Can return different types:

& gt; & gt; & gt; Filter (None, "ABC")
'ABC'
& gt; & gt; & gt; Filter (None, [1,2,3])
[1, 2, 3]
& gt; & gt; & gt; Filter (None, (1,2,3))
(1, 2, 3)

in python 3, Filter () Already returns iterator as and Reversed () :

& gt; & gt; & gt; Filter (None, "ABC")
& lt; Filter Object at 0x7Fe43B586F60 & gt;
& gt; & gt; & gt; List (_)
['A', 'B', 'C']

Possible explanation: the use of iterators saves memory (you do not need to hold the entire reverse sequence in memory immediately) and is more general (there is no special processing of built-in type subclasses such as str , List , Tuple ). Reversed () Later function (only in Python 2.4 appeared) Therefore, its interface is more universal with an emphasis on a more economical general and simple implementation.


Answer 2, Authority 33%

The fact is that Reversed returns an iterator to a reverse string. Look in the documentation: https://docs.python.org/2/library/Functions .html # Reversed


Answer 3, Authority 33%

@Anton,

How to remark the previous stacking, reversed () Returns the iterator, so you need to determine the function call in list () or Tuple () .

And now practice:

s = 'abc'
Print (REVERSED (S)))

Displays: ['C', 'B', 'A']

Iterators are useful in cycles for , generators and similar. So when around the sequence, for example, wrapping in list () nothing.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions