listTest1 = [5, 4, 3, 2, 1] Show
print("list before reversing: ") # call reverse on first list print("\nlist after reversing: ") print(listTest1) # list is updated listTest2 = ["one", "two", "three", "four", "five"] print("\nlist before reversing: ") # call reverse on second list print("\nlist after reversing: ") print(listTest2) # list is updated # this will throw Attribute Error # calling reverse with an onject that is not a list When you’re using Python strings often in your code, you may face the need to work with them in reverse order. Python includes a few handy tools and techniques that can help you out in these situations. With them, you’ll be able to build reversed copies of existing strings quickly and efficiently. Knowing about these tools and techniques for reversing strings in Python will help you improve your proficiency as a Python developer. In this tutorial, you’ll learn how to:
To make the most out of this tutorial, you should know the basics of strings, 3 and 4 loops, and recursion.Free Download: Get a sample chapter from Python Basics: A Practical Introduction to Python 3 to see how you can go from beginner to intermediate in Python with a complete curriculum, up-to-date for Python 3.8. Reversing Strings With Core Python ToolsWorking with Python strings in reverse order can be a requirement in some particular situations. For example, say you have a string 5 and you want a fast way to reverse it to get 6. What Python tools can you use to help?Strings are in Python, so reversing a given string in place isn’t possible. You’ll need to create reversed copies of your target strings to meet the requirement. Python provides two straightforward ways to reverse strings. Since strings are sequences, they’re indexable, sliceable, and iterable. These features allow you to use to directly generate a copy of a given string in reverse order. The second option is to use the built-in function to create an iterator that yields the characters of an input string in reverse order. Remove adsReversing Strings Through SlicingSlicing is a useful technique that allows you to extract items from a given sequence using different combinations of integer indices known as offsets. When it comes to slicing strings, these offsets define the index of the first character in the slicing, the index of the character that stops the slicing, and a value that defines how many characters you want to jump through in each iteration. To slice a string, you can use the following syntax:
Your offsets are 8, 9, and 0. This expression extracts all the characters from 8 to 2 by 0. You’re going to look more deeply at what all this means in just a moment.All the offsets are optional, and they have the following default values: OffsetDefault Value 8 5 9 7 0 9Here, 8 represents the index of the first character in the slice, while 9 holds the index that stops the slicing operation. The third offset, 0, allows you to decide how many characters the slicing will jump through on each iteration.Note: A slicing operation finishes when it reaches the index equal to or greater than 9. This means that it never includes the item at that index, if any, in the final slice.The 0 offset allows you to fine-tune how you extract desired characters from a string while skipping others:>>>
Here, you first slice 5 without providing explicit offset values to get a full copy of the original string. To this end, you can also use a slicing that omits the second colon ( 6). With 0 equal to 8, the slicing gets every other character from the target string. You can play around with different offsets to get a better sense of how slicing works.Why are slicing and this third offset relevant to reversing strings in Python? The answer lies in how 0 works with negative values. If you provide a negative value to 0, then the slicing runs backward, meaning from right to left.For example, if you set 0 equal to 2, then you can build a slice that retrieves all the characters in reverse order:>>>
This slicing returns all the characters from the right end of the string, where the index is equal to 3, back to the left end of the string, where the index is 5. When you use this trick, you get a copy of the original string in reverse order without affecting the original content of 5.Another technique to create a reversed copy of an existing string is to use . The signature of this built-in function is the following:
This function takes three arguments, with the same meaning of the offsets in the slicing operator, and returns a object representing the set of indices that result from calling 7.You can use 6 to emulate the slicing 9 and reverse your strings quickly. Go ahead and run the following call to 6 inside square brackets:>>>
Passing 1 to the first two arguments of 6 tells the function that you want to rely on its internal default behavior, which is the same as a standard slicing with no values for 8 and 9. In other words, passing 1 to 8 and 9 means that you want a slice from the left end to the right end of the underlying sequence.Remove adsReversing Strings With >>> letters = "ABCDEF" >>> letters[::-1] 'FEDCBA' >>> letters 'ABCDEF' 1 and >>> letters = "ABCDEF" >>> letters[::-1] 'FEDCBA' >>> letters 'ABCDEF' 0The second and arguably the most Pythonic approach to reversing strings is to use 0 along with . If you pass a string to 0, you get an iterator that yields characters in reverse order:>>>
When you call 3 with 4 as an argument, you get each character from the right end of the original string.An important point to note about 0 is that the resulting iterator yields characters directly from the original string. In other words, it doesn’t create a new reversed string but reads characters backward from the existing one. This behavior is fairly efficient in terms of memory consumption and can be a fundamental win in some contexts and situations, such as iteration.You can use the iterator that you get from calling 0 directly as an argument to 1:>>>
In this single-line expression, you pass the result of calling 0 directly as an argument to 1. As a result, you get a reversed copy of the original input string. This combination of 0 and 1 is an excellent option for reversing strings.Generating Reversed Strings by HandSo far, you’ve learned about core Python tools and techniques to reverse strings quickly. Most of the time, they’ll be your way to go. However, you might need to reverse a string by hand at some point in your coding adventure. In this section, you’ll learn how to reverse strings using explicit loops and recursion. The final technique uses a functional programming approach with the help of Python’s 2 function.Reversing Strings in a LoopThe first technique you’ll use to reverse a string involves a 3 loop and the concatenation operator ( 4). With two strings as operands, this operator returns a new string that results from joining the original ones. The whole operation is known as concatenation.Note: Using 1 is the recommended approach to concatenate strings in Python. It’s clean, efficient, and Pythonic.Here’s a function that takes a string and reverses it in a loop using concatenation: >>>
In every iteration, the loop takes a subsequent character, 6, from 7 and concatenates it with the current content of 8. Note that 8 initially holds an empty string ( 0). The new intermediate string is then reassigned to 8. At the end of the loop, 8 holds a new string as a reversed copy of the original one.Note: Since Python strings are immutable data types, you should keep in mind that the examples in this section use a wasteful technique. They rely on creating successive intermediate strings only to throw them away in the next iteration. If you prefer using a 4 loop, then here’s what you can do to build a reversed copy of a given string:>>>
Here, you first compute the 4 of the last character in the input string by using 5. The loop iterates from 4 down to and including 5. In every iteration, you use the operator ( 8) to create an intermediate string that concatenates the content of 8 with the corresponding character from 7. Again, the final result is a new string that results from reversing the input string.Reversing Strings With RecursionYou can also use recursion to reverse strings. Recursion is when a function calls itself in its own body. To prevent infinite recursion, you should provide a base case that produces a result without calling the function again. The second component is the recursive case, which starts the recursive loop and performs most of the computation. Here’s how you can define a recursive function that returns a reversed copy of a given string: >>>
In this example, you first check for the base case. If the input string has exactly one character, you return the string back to the caller. The last statement, which is the recursive case, calls 01 itself. The call uses the slice 02 of the input string as an argument. This slice contains all the characters in 7, except for the first one. The next step is to add the result of the recursive call together with the single-character string 04, which contains the first character of 7.A significant issue to note in the example above is that if you pass in a long string as an argument to 01, then you’ll get a 07:>>> 0Hitting Python’s default recursion limit is an important issue that you should consider in your code. However, if you really need to use recursion, then you still have the option to set the recursion limit manually. You can check the recursion limit of your current Python interpreter by calling from . By default, this value is usually 10. You can tweak this limit using from the same module, 09. With these functions, you can configure the Python environment so that your recursive solution can work. Go ahead and give it a try!Using >>> def reversed_string(text): ... result = "" ... index = len(text) - 1 ... while index >= 0: ... result += text[index] ... index -= 1 ... return result ... >>> reversed_string("Hello, World!") '!dlroW ,olleH' 2 to Reverse StringsIf you prefer using a functional programming approach, you can use 2 from to reverse strings. Python’s 2 takes a folding or reduction function and an iterable as arguments. Then it applies the provided function to the items in the input iterable and returns a single cumulative value.Here’s how you can take advantage of 2 to reverse strings:>>> 1In this example, the 18 function takes two strings and concatenates them in reverse order. The call to 2 applies the 18 to 7 in a loop and builds a reversed copy of the original string.Iterating Through Strings in ReverseSometimes you might want to iterate through existing strings in reverse order, a technique typically known as reverse iteration. Depending on your specific needs, you can do reverse iteration on strings by using one of the following options:
Reverse iteration is arguably the most common use case of these tools, so in the following few sections, you’ll learn about how to use them in an iteration context. The >>> letters = "ABCDEF" >>> letters[::-1] 'FEDCBA' >>> letters 'ABCDEF' 0 Built-in FunctionThe most readable and Pythonic approach to iterate over a string in reverse order is to use 0. You already learned about this function a few moments ago when you used it along with 1 to create reversed strings.However, the main intent and use case of 0 is to support reverse iteration on Python iterables. With a string as an argument, 0 returns an iterator that yields characters from the input string in reverse order.Here’s how you can iterate over a string in reverse order with 0:>>> 2The 3 loop in this example is very readable. The name of 0 clearly expresses its intent and communicates that the function doesn’t produce any side effects on the input data. Since 0 returns an iterator, the loop is also efficient regarding memory usage.Remove adsThe Slicing Operator, >>> greeting = reversed("Hello, World!") >>> next(greeting) '!' >>> next(greeting) 'd' >>> next(greeting) 'l' 9The second approach to perform reverse iteration over strings is to use the extended slicing syntax you saw before in the 34 example. Even though this approach won’t favor memory efficiency and readability, it still provides a quick way to iterate over a reversed copy of an existing string:>>> 3In this example, you apply the slicing operator on 4 to create a reversed copy of it. Then you use that new reversed string to feed the loop. In this case, you’re iterating over a new reversed string, so this solution is less memory-efficient than using 0.Creating a Custom Reversible StringIf you’ve ever tried to reverse a Python list, then you know that lists have a handy method called 37 that reverses the underlying list in place. Since strings are immutable in Python, they don’t provide a similar method.However, you can still create a custom string subclass with a 37 method that mimics 39. Here’s how you can do that:>>> 4 40 inherits from 41, which is a class from the 42 module. 41 is a wrapper around the built-in data type. It was specially designed for creating subclasses of 44. 41 is handy when you need to create custom string-like classes with additional functionalities. 41 provides the same functionality as a regular string. It also adds a public attribute called 48 that holds and gives you access to the wrapped string object.Inside 40, you create 37. This method reverses the wrapped string in 48 and reassigns the result back to 48. From the outside, calling 37 works like reversing the string in place. However, what it actually does is create a new string containing the original data in reverse order.Here’s how 40 works in practice:>>> 5When you call 37 on 7, the method acts as if you’re doing an in-place mutation of the underlying string. However, you’re actually creating a new string and assigning it back to the wrapped string. Note that 7 now holds the original string in reverse order.Since 41 provides the same functionality as its superclass 44, you can use 0 out of the box to perform reverse iteration:>>> 6Here, you call 0 with 7 as an argument to feed a 3 loop. This call works as expected and returns the corresponding iterator because 41 inherits the required behavior from 44. Note that calling 0 doesn’t affect the original string.Sorting Python Strings in Reverse OrderThe last topic you’ll learn about is how to sort the characters of a string in reverse order. This can be handy when you’re working with strings in no particular order and you need to sort them in reverse alphabetical order. To approach this problem, you can use 2. This built-in function returns a list containing all the items of the input iterable in order. Besides the input iterable, 2 also accepts a 69 keyword argument. You can set this argument to 70 if you want the input iterable to be sorted in descending order:>>> 7When you call 2 with a string as an argument and 69 set to 70, you get a list containing the characters of the input string in reverse or descending order. Since 2 returns a 75 object, you need a way to turn that list back into a string. Again, you can use 1 just like you did in earlier sections:>>> 8In this code snippet, you call 1 on an empty string, which plays the role of a separator. The argument to 1 is the result of calling 2 with 80 as an argument and 69 set to 70.You can also take advantage of 2 to iterate through a string in sorted and reversed order:>>> 9The 69 argument to 2 allows you to sort iterables, including strings, in descending order. So, if you ever need a string’s characters sorted in reverse alphabetical order, then 2 is for you.Remove adsConclusionReversing and working with strings in reverse order can be a common task in programming. Python provides a set of tools and techniques that can help you perform string reversal quickly and efficiently. In this tutorial, you learned about those tools and techniques and how to take advantage of them in your string processing challenges. In this tutorial, you learned how to:
Even though this topic might not have many exciting use cases by itself, understanding how to reverse strings can be useful in coding interviews for entry-level positions. You’ll also find that mastering the different ways to reverse a string can help you really conceptualize the immutability of strings in Python, which is a notable feature of the language. Mark as Completed 🐍 Python Tricks 💌 Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team. Send Me Python Tricks » About Leodanis Pozo Ramos Leodanis is an industrial engineer who loves Python and software development. He's a self-taught Python developer with 6+ years of experience. He's an avid technical writer with a growing number of articles published on Real Python and other sites. » More about LeodanisEach tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are: Aldren Bartosz Sadie Master Real-World Python Skills With Unlimited Access to Real Python Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas: Level Up Your Python Skills » Master Real-World Python Skills Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas: Level Up Your Python Skills » What Do You Think? Rate this article: Tweet Share Share EmailWhat’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know. Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. and get answers to common questions in our support portal. What is reversed function?The REVERSE function accepts a character expression as its argument, and returns a string of the same length, but with the ordinal positions of every logical character reversed.
What is the difference between reverse and reversed () in Python?reverse() actually reverses the elements in the container. reversed() doesn't actually reverse anything, it merely returns an object that can be used to iterate over the container's elements in reverse order.
What is the use of reverse () method in the list?The reverse() method reverses the sorting order of the elements.
|