How To Reverse A List Of Strings In Python

In this tutorial, we will learn how to reverse a list of strings in Python. Reversing a list can be useful in many situations, such as when you need to reverse the order of data in a file, or when creating a palindrome check.

With Python’s built-in functions and list comprehensions, this task can be performed efficiently and easily.

Step 1: Create a List of Strings

First, let’s create a list of strings in Python. You can either hard-code a list of strings or create a list by reading from a file. For this tutorial, we will use a hard-coded list:

Step 2: Use Built-in Reverse Function

One way to reverse a list of strings is by using the built-in reverse() function. This function reverses the order of the elements in the list in place, meaning that it modifies the original list without creating a new list. Here is how to reverse the list using the reverse() function:

After calling string_list.reverse(), the string_list variable now contains the reversed list:

["fig", "date", "cherry", "banana", "apple"]

Step 3: Use List Slicing

Another way to reverse a list of strings is by using list slicing with a stride of -1. Using a negative stride means that you are slicing the list from end to beginning. With a stride of -1, you are slicing in steps of -1, which will give you the reversed list. Here is how to reverse the list using list slicing:

In this case, the reversed_list variable contains the reversed list:

["fig", "date", "cherry", "banana", "apple"]

The original string_list remains unchanged.

Step 4: Use the Built-in Reversed Function

You can also use the built-in reversed() function, which returns a reversed iterator object. To get a list from the iterator object, you need to convert it to a list using the list() function:

In this case, the reversed_list variable also contains the reversed list:

["fig", "date", "cherry", "banana", "apple"]

Again, the original string_list remains unchanged.

Full Code

Output

["fig", "date", "cherry", "banana", "apple"]
["apple", "banana", "cherry", "date", "fig"]
["apple", "banana", "cherry", "date", "fig"]

Conclusion

In this tutorial, we learned three methods for reversing a list of strings in Python: using the reverse() function, using list slicing, and using the reversed() function.

Among these three methods, list slicing and the reversed() function are non-destructive, meaning they don’t modify the original list, which can be useful if you need to keep your original list unchanged.

The reverse() function, on the other hand, is quicker in terms of memory usage, as it is an in-place reversal. You can choose the method that best suits your needs and the context in which you are working.