-1

Why is the second print command giving an empty list while the first is giving proper output?

str1 = 'Hello'

str2 = reversed(str1)

print(list(str2))
print(list(str2))

Output:

['o', 'l', 'l', 'e', 'H']
[]
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Related: [this post](https://stackoverflow.com/questions/65738468/why-am-i-getting-the-valueerror/65738510#65738510) from just 2 days ago -- though in that case it was `filter` (same principle though). – costaparas Jan 18 '21 at 12:31

2 Answers2

4

reversed is an iterator, iterators can be consumed only once meaning once you iterate over them, you cannot do it again.

Check the documentation

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Gaëtan GR
  • 1,380
  • 1
  • 5
  • 21
1

Cause for [] (empty list)

The built-in reversed, is an iterator, so it get exhausted once you have consumed it, by making a list. In your case, once you make it a do, list(revered("Hello")), it becomes, exhausted.

Solution

A quick solution could be making another iterator, code:

str1 = "Hello" # Original String 

iter1 = reversed(str1) # Making the first iterator 
iter2 = reversed(str1) # Making the second iterator 

print(list(iter1), list(iter2)) # Printing the iterator once they are lists
abhigyanj
  • 2,355
  • 2
  • 9
  • 29
  • The more common solution is to turn the iterator to a list: `str2 = list(reversed(str1))` – Tomerikoo Jan 18 '21 at 13:48
  • It seems wasteful to call `reversed` twice. You almost always want to re-use the reversed list (perhaps multiple times) in the code, so its worth calling `list` to convert it immediately. – costaparas Jan 18 '21 at 14:51