Why can't I return it to the str() built-in function after the reversed() function?

Viewed 98
a = '123asdad'


str(reversed(a))
>> '<reversed object at 0x00000206C9F80250>'


list(reversed(a))
>> ['d', 'a', 'd', 's', 'a', '3', '2', '1']

I already know that the best way is a[::-1].

But I want to know why I can't convert the reversed object into a str() function. list() or tuple() is possible, but why not str()?

All three are iterable objects and Seqence type objects, is there anything I don't know?

2 Answers

All three are iterable objects and Seqence type objects, is there anything I don't know?

You're correct, they're all iterable objects, but they each have a different implementation of __str__.

If you expect str(reversed(a)) to return "['d', 'a', 'd', 's', 'a', '3', '2', '1']", then what you're essential asking is for the reversed class to have the same behaviour of __str__ as list.

This would actually be quite confusing, because it would blur the distinction between objects of reversed and list. They're intentionally different. A reversed object wraps an underlying collection and behaves as if it had reversed all the elements in memory, without actually wasting CPU/memory to reverse all the elements in memory.

If you do want the list behaviour of __str__, then use it:

str(list(reversed(a)))

Of course, you should notice that this ends up doing all the reversing for real, copying the elements into a new list in the reversed order. If that's undesirable, then you'll have to implement your own formatting code to iterate a reversed object (or any iterable, really), quoting its elements, joining them with , and surrounding them with [ ].

str calls the __str__ function on the object (which is what is called when the object is printed, so there is no difference between the output of str(reversed(a)) and reversed(a) in a REPL).


The __str__ function is automatically generated if neither that nor the __repr__ function is provided.

You can see this here:

class Foo:
    pass

my_obj = Foo()
print(my_obj)

Output: <__main__.Foo object at 0x7ffa890ab5e0>

The reversed class doesn't provide a __str__ function, so str(reversed(a)) will return the automatically generated value


Use ''.join(reversed(a)) to get the desired output:

>>> a = '123asdad'
>>> ''.join(reversed(a))
'dadsa321'
Related