Reverse a List Using Slicing in Python

To reverse a list using slicing in Python, you can use the slice notation [::-1], which creates a new list with elements in reversed order. This approach is simple, efficient, and does not modify the original list unless explicitly reassigned.


Example

Reversing a List Using Slicing

In this example, we will define a list and use slicing to reverse it.

</>
Copy
# Creating a list
numbers = [1, 2, 3, 4, 5]

# Reversing the list using slicing
reversed_numbers = numbers[::-1]

# Printing the original and reversed lists
print("Original List:", numbers)
print("Reversed List:", reversed_numbers)

In this example:

  • numbers: This is our original list containing [1, 2, 3, 4, 5].
  • [::-1]: This is Python’s slicing notation, where:
  • reversed_numbers: This new list stores the reversed version of numbers.

Since slicing returns a new list, the original numbers list remains unchanged. If you want to modify the list in place, you can assign the reversed list back to numbers as follows:

</>
Copy
# Reversing in place
numbers = numbers[::-1]

Output

Original List: [1, 2, 3, 4, 5]
Reversed List: [5, 4, 3, 2, 1]

Using slicing with [::-1] provides a quick and memory-efficient way to reverse a list in Python without requiring loops or additional functions.