I created my own iterator (to learn how they work) as follows
class Reverse():
def __init__(self, word):
self.word = word
self.index = len(word)
def __iter__(self):
return self
def __next__(self):
self.index -=1
if self.index < 0:
raise StopIteration
return self.word[self.index]
print (char for char in Reverse("word"),end="")
I know I can say:
rev = Reverse("word")
for char in rev:
print(char, end="")
but I was hoping to be able to do it in a single line
print (char for char in Reverse("word"),end="")
This doesn't work and raises an error. If I remove the end=""
it prints out a generator object
. Surely by including a for loop
in the print
statement it should iterate through my generator object and print each item?
Why does this not happen