3

Why list is used while printing? Without using list why can't we just print the reverse string?

My code:

name = "prajwal"
name1 = reversed(name)
print(list(name1))

#result:
['l', 'a', 'w', 'j', 'a', 'r', 'p']
Adirio
  • 5,040
  • 1
  • 14
  • 26

1 Answers1

3

The reversed function returns an iterator, not a string. Iterators are special Python objects made to iterate over something (that may be more complicated than a list or a string). You can learn more here.

If you want to reverse a string you can do:

name1 = name[::-1]
Gustave Coste
  • 677
  • 5
  • 19
  • `reversed` is actually a class; calling it can return an instance of `reversed`, or an instance of some other type according to its argument's `__reversed__` method. In any case, that object will implement the iterator protocol, which just means it can be passed to `iter` to get an iterable object. – chepner Sep 03 '20 at 12:23
  • Probably; I can never keep "iterator" and "iterable" straight. – chepner Sep 03 '20 at 12:36