Reputation: 348
>>> x = "hello world"
>>> y = reversed(x)
>>> z = ''.join(y)
>>> z
'dlrow olleh'
>>> y
<reversed object at 0x7f2871248b38>
>>> ''.join(y)
''
>>> x
'hello world'
>>> ''.join(y)
''
>>> z = ''.join(y)
>>> z
''
Why I am getting the value of z next time as blank string after doing join operation in reversed function
Upvotes: 0
Views: 36
Reputation: 6149
This is because reversed returns an iterator, when you apply an operation on it, it "consumes" the element. If you want to store the result of reversed in a variable, join is a good way to do it.
from collections.abc import Iterator
print(isinstance(reversed("hello world"), Iterator)) # True
it = reversed("hello world")
for x in it:
print(x) # Prints the letters
for x in it:
print(x) # Do not print them, there are already "consumed"
Upvotes: 2