Python List – Slice reverse

Python – Reverse a List using Slicing

To reverse a given List x in Python using Slicing technique, use the following syntax.

x[::-1]

The above expression does not modify the original list x, but returns a new list with the elements of the list x in reversed order.

Let see examine the slicing notation. The syntax to slicing notation is

[start:stop:step]

In the following slicing expression

[::-1]

We have left the start and stop to their default values, and specified a step value of -1.

Examples

1. Reverse the given list of numbers using slicing in Python

In this example, we take a List of numbers, and reverse the list using slicing technique.

Python Program

# Given list
my_list = [2, 4, 6, 8]

# Reverse the list using slicing
reversed_list = my_list[::-1]

# Print reversed list
print(reversed_list)
Run Code Copy

Output

[8, 6, 4, 2]

2. Reverse the given list of strings using slicing in Python

In this example, we take a List of strings, and reverse the list using slicing technique.

Python Program

# Given list
my_list = ['apple', 'banana', 'cherry']

# Reverse the list using slicing
reversed_list = my_list[::-1]

# Print reversed list
print(reversed_list)
Run Code Copy

Output

['cherry', 'banana', 'apple']
Run Code Copy

Summary

In this tutorial of Python Examples, we learned how to reverse a Python List using slicing technique, with the help of well detailed example programs.

Related Tutorials

Code copied to clipboard successfully 👍