How To Reverse Sequence In Python

Reversing a sequence is a common programming task that comes up in various contexts.

In Python, there are several ways to reverse a sequence, such as a list, tuple, or string.

In this tutorial, we will cover different methods to reverse a sequence in Python, including using the reverse() function, slicing techniques, and the reversed() function.

Method 1: Using the reverse() function

Step 1: Create a list

Let’s begin by creating a simple list of integers.

Step 2: Use the reverse() function

The reverse() function modifies the original list in place by reversing its elements. To reverse the number_list, simply call the reverse() function on it.

Step 3: Display the reversed list

Now, let’s print the reversed list to verify the changes.

[5, 4, 3, 2, 1]

Method 2: Using slicing

Step 1: Create a list or string

First, let’s create a list of integers or a string that you want to reverse.

Step 2: Reverse the sequence using slicing

Python offers a simple and quick way to reverse any sequence using slicing. Just add [::-1] at the end of the sequence.

Step 3: Display the reversed sequence

Now, let’s print the reversed list or string to verify the outcome.

[5, 4, 3, 2, 1]
olleh

Method 3: Using the reversed() function

Step 1: Create a list or tuple

Let’s create a list or tuple to reverse using the reversed() function.

Step 2: Reverse the sequence using the reversed() function

The reversed() function returns a reverse iterator. You can iterate through the reversed elements, or you can convert the iterator back to a list or tuple using the list() or tuple() functions.

Step 3: Display the reversed sequence

Finally, let’s print the reversed list or tuple to verify the changes.

[5, 4, 3, 2, 1]
(5, 4, 3, 2, 1)

Full Code

Conclusion

In this tutorial, we have explored three different methods to reverse a sequence in Python, including using the reverse() function, slicing techniques, and the reversed() function. Each method has its own strengths and limitations depending on the type of sequence and whether you want to modify the original sequence in place or create a new reversed sequence.