@tbhesswebber The function should return a string (and not print anything). But that value isn't a string. If you want to print the result of the function, then do exactly that:
print reverse('hello') - printing is otherwise pretty useless if you want to use the result in other parts of your code.
Oh. I thought it would only do that in Python3.
Instead of returning a string,
reversed returns an iterator, which needs to be consumed to produce the characters in reversed order.
str.join will accept iterables/iterators:
(a list is an iterable, so a list of characters treated the same way as the reversed object)
i = reversed('hello')
print next(i) # o
print next(i) # l
print next(i) # l
print next(i) # e
print next(i) # h
print next(i) # StopIteration exception, meaning it's exhausted
The above is essentially what a for-loop does. If the value is not an iterator but is iterable, then an iterator needs to be requested first by doing:
We could for example make an iterable integer, let's say it should count from 0 up/down to itself by inheriting everything that int has, and adding the
i = 0
while i != self:
i += 1 if self > 0 else -1
# Try iterating "through" our integer:
for n in MyInt(4):
A whole lot is going on there.
The first line says that
MyInt is a class and it inherits
int. So instances of
MyInt are also
int's - this is what allows me to use
> and also why I can do
MyInt(4) - because
int(4) creates the int
4 and I'm inheriting that behaviour.
yield statement turns
__iter__ into a generator, When it is called, its code does not run. Instead, an iterator is created and returned. Each time next vaule is requested from that iterator, the code in
__iter__ will run until it hits
yield - at which point it returns a value and pauses its execution state so that it can continue where it left off next time a value is requested.
Once control reaches the end of the code in
StopIteration gets raised and that's how one knows that it has been exhausted.
A result of that
reversed does not return a string, but an iterator, is that it will finish in the same amount of time regardless of the size of what is to be reversed. Because all it does is to create an iterator - the actual reversing only happens as you request the values one at a time.