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
s = 'hello'
Let’s see how we can do this.
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
# 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
# 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 [0, len(s)) backwards for i in range(0, len(s), -1): print(s[i]) # 'o', 'l', 'l', 'e'
We can reverse a string in-place using the
s.reverse() # None for char in s: print(char) # 'o', 'l', 'l', 'e', 'h'
Every iterable object in Python has this slicing feature.
Similar to the
range() definition, the slicing feature is defined as follows:
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
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.
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'
More Python Articles
- How to Start an HTTP Server in Python
- How to Get All Keys with the Highest Value in Python
- How to Check if a Tuple Exists in a List in Python
- How to Sort a List of Dictionaries By Field in Python
- How to Sort a Dictionary by Value in Python
- How to Flatten a 2D List in Python
- How to Sort a List of Tuples Based on Multiple Elements
- How to Remove Duplicates from a List in Python
- How to Set Multiple Values of a List in Python
- How to Remove the Last N Elements of a List in Python
- How to Get the ASCII Value of a Character in Python
- How to Create a Two Dimensional List in Python
- How to Migrate Data from MongoDB to Elasticsearch in Python
- How to Add Key-Value to Dictionary During List Comprehension in Python
- How to Fix "datetime is not JSON serializable" TypeError in Python
- How to Remove a Key From a Dictionary in Python
- Encoding and Decoding Bytes Explained
- How to Paginate/Scroll Elasticsearch Data using Python
- How to Print Without Newline in Python 3
- How to Get the Key with the Maximum Value in Python
- List Comprehension in Python Explained Visually
- How to Check if a String Contains Another String in Python
- What is Enumerate in Python?
- What is the Difference Between List and Tuple in Python?