11

I'm trying to get used to iterators. Why if I type

b = list(reversed([1,2,3,4,5]))

It will give me a reversed list, but

c = str(reversed('abcde'))

won't give me a reversed string?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Yunti
  • 6,761
  • 12
  • 61
  • 106
  • you need to iterate over the reversed object, which is what you do by calling list on it, `str(reversed('abcde')) ` will give you the object as a string the same as `str([])` etc.. does – Padraic Cunningham Feb 20 '15 at 15:49
  • Related: [Reverse a string in Python](http://stackoverflow.com/q/931092/1497596) – DavidRR Feb 20 '15 at 16:21
  • Please go through your questions and see if there are answers deserve being accepted (as the one in this topic). – alecxe Apr 01 '15 at 17:27

2 Answers2

12

In Python, reversed actually returns a reverse iterator. So, list applied on the iterator will give you the list object.

In the first case, input was also a list, so the result of list applied on the reversed iterator seemed appropriate to you.

In the second case, str applied on the returned iterator object will actually give you the string representation of it.

Instead, you need to iterate the values in the iterator and join them all with str.join function, like this

>>> ''.join(reversed('abcde'))
edcba
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • Thanks I'm not sure what the string representation is vs the string? Does using join work because it is iterating through the reversed string to rebuild it (excuse my poor terminology), whereas str() isn't doing this? – Yunti Feb 20 '15 at 16:47
  • Str ll try to convert the object to a string. Since the reverse iterator is an object, it would be tried to converted to a string. But join iterates the iterator and builds a new string with all the strings from the iterator – thefourtheye Feb 20 '15 at 16:51
  • Thanks so str() doesn't iterate to build a new string, like list does to build a list. How does str() build or covert a string? Is the difference due to a string being immutable vs list is mutable so a str() can't rebuild a string in the same way – Yunti Feb 20 '15 at 16:59
  • Str internally calls the `__str__` magic method to get the string representation. – thefourtheye Feb 20 '15 at 17:02
4

another way by extend slice method. more details

>>> a = "abcde"
>>> a[::-1]
'edcba'
>>> 

by string to list --> list reverse --> join list

>>> a
'abcde'
>>> b = list(a)
>>> b
['a', 'b', 'c', 'd', 'e']
>>> b.reverse()
>>> b
['e', 'd', 'c', 'b', 'a']
>>> "".join(b)
'edcba'
>>> 
Vivek Sable
  • 9,938
  • 3
  • 40
  • 56