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']
[]
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']
[]
 
    
    reversed is an iterator, iterators can be consumed only once meaning once you iterate over them, you cannot do it again.
[] (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.
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
