Use Slicing for Reversal
In this step, you will focus specifically on how slicing is used to reverse a list in Python. Slicing is a powerful feature that allows you to extract portions of a list, and it can also be used to create a reversed copy of the list.
Let's revisit the palindrome.py
file and examine the slicing technique more closely.
-
Open the palindrome.py
file in your VS Code editor.
-
Ensure the content of the palindrome.py
file is as follows:
def is_palindrome(lst):
reversed_lst = lst[::-1]
return lst == reversed_lst
## Example lists
list1 = [1, 2, 3, 2, 1]
list2 = [1, 2, 3, 4, 5]
## Check if the lists are palindromes
print(f"{list1} is a palindrome: {is_palindrome(list1)}")
print(f"{list2} is a palindrome: {is_palindrome(list2)}")
The key part of this code is lst[::-1]
. This is a slicing operation that creates a reversed copy of the list. Let's break it down:
lst[:]
would create a copy of the entire list.
lst[start:end]
would create a slice from index start
to end-1
.
lst[start:end:step]
allows you to specify a step
. A step of -1
means to iterate backwards through the list.
- By omitting
start
and end
and using a step of -1
(i.e., lst[::-1]
), you create a reversed copy of the entire list.
To further illustrate this, let's add some print statements to see the effect of slicing:
def is_palindrome(lst):
reversed_lst = lst[::-1]
print(f"Original list: {lst}")
print(f"Reversed list: {reversed_lst}")
return lst == reversed_lst
## Example lists
list1 = [1, 2, 3, 2, 1]
list2 = [1, 2, 3, 4, 5]
## Check if the lists are palindromes
print(f"{list1} is a palindrome: {is_palindrome(list1)}")
print(f"{list2} is a palindrome: {is_palindrome(list2)}")
Now, run the script again:
python ~/project/palindrome.py
You will see the original and reversed lists printed before the palindrome check result:
Original list: [1, 2, 3, 2, 1]
Reversed list: [1, 2, 3, 2, 1]
[1, 2, 3, 2, 1] is a palindrome: True
Original list: [1, 2, 3, 4, 5]
Reversed list: [5, 4, 3, 2, 1]
[1, 2, 3, 4, 5] is a palindrome: False
This demonstrates how slicing with [::-1]
effectively reverses the list, which is then used to determine if the original list is a palindrome.