Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 369
형한결 Avatar asked Oct 25 '25 10:10

형한결


1 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 [ ].

like image 91
Alexander Avatar answered Oct 27 '25 22:10

Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!