How to Loop Over a String in Reverse in Python


We’ve all had to iterate backwards over a string at some point, whether it’s in a project itself or a coding interview.

Suppose we’re iterating backwards over the string s, which we define as hello.

s = 'hello'

Let’s see how we can do this.

Using range()

The definition of range() looks like this:

range(?start, stop, ?step)

When we only have one parameter, that defines our stop value (our start value defaults to 0).

# Iterates from [0, len(s))
for i in range(len(s)):
    print(s[i]) # 'h', 'e', 'l', 'l', 'o'

When we have two parameters, they defines our start and stop values.

# Iterates from [1, len(s))
for i in range(1, len(s)):
    print(s[i]) # 'e', 'l', 'l', 'o'

When we use all three parameters, we can specify our step interval, which can be -1 to define a backwards iteration.

# Iterates [len(s)-1, -1) backwards
for i in range(len(s)-1, -1, -1):
    print(s[i]) # 'o', 'l', 'l', 'e', 'h'

Using string.reverse()

We can reverse a string in-place using the string.reverse() method.

s.reverse() # None
for char in s:
    print(char) # 'o', 'l', 'l', 'e', 'h'

Using [::-1]

Every iterable object in Python has this slicing feature.

Similar to the range() definition, the slicing feature is defined as follows:

[start:stop:step]

We can create a reversed copy of a string using this slicing technique, which looks something like this:

for char in s[::-1]:
    print(char) # 'o', 'l', 'l', 'e', 'h'

We are copying the entire string (as defined by the empty indexes for start and stop) backwards (as defined by the -1 step interval).

However, this method requires much more memory compared to any of the other options. It creates a shallow copy of the object at hand. This means that we’re simply copying the references from the original list.

Any change made to the original list will be reflected in this copied list as well.

Using reversed()

The last option is to use reversed(), which creates a reverse iterator. The string is never actually reversed, and there is no actual copy made.

We just cycle through the string in reverse order.

for char in reversed(s):
    print(char) # 'o', 'l', 'l', 'e', 'h'