How to Check If a List Is a Palindrome in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to determine if a list is a palindrome in Python. A palindrome is a sequence that reads the same forwards and backward. The lab guides you through creating a Python script to identify list palindromes.

You'll explore two methods: comparing a list with its reversed version using slicing, and explicitly reversing the list for comparison. The lab provides code examples and instructions on how to run the script and interpret the output, demonstrating whether given lists are palindromes or not.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/DataStructuresGroup -.-> python/lists("Lists") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/lists -.-> lab-559532{{"How to Check If a List Is a Palindrome in Python"}} python/function_definition -.-> lab-559532{{"How to Check If a List Is a Palindrome in Python"}} python/data_collections -.-> lab-559532{{"How to Check If a List Is a Palindrome in Python"}} end

Understand List Palindromes

In this step, you will learn about list palindromes and how to identify them in Python. A palindrome is a sequence that reads the same forwards and backward. For example, the word "madam" is a palindrome. In the context of lists, a list palindrome is a list whose elements are the same when read from the beginning to the end or from the end to the beginning.

Let's start by creating a Python script to explore list palindromes.

  1. Open your VS Code editor.

  2. Create a new file named palindrome.py in the ~/project directory.

    touch ~/project/palindrome.py
  3. Open the palindrome.py file in the editor.

Now, let's add some code to the palindrome.py file to understand how to check if a list is a palindrome.

def is_palindrome(lst):
    return lst == lst[::-1]

## 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)}")

In this code:

  • We define a function is_palindrome(lst) that takes a list lst as input.
  • Inside the function, we compare the list with its reversed version using slicing lst[::-1].
  • The function returns True if the list is a palindrome and False otherwise.
  • We create two example lists, list1 which is a palindrome, and list2 which is not.
  • We use the print() function to display whether each list is a palindrome or not.

To run the script, execute the following command in the terminal:

python ~/project/palindrome.py

You should see the following output:

[1, 2, 3, 2, 1] is a palindrome: True
[1, 2, 3, 4, 5] is a palindrome: False

This output confirms that list1 is a palindrome, and list2 is not.

Compare with Reversed List

In this step, you will explore another method to check if a list is a palindrome by explicitly reversing the list and comparing it with the original list. This approach provides a more detailed understanding of the palindrome check.

Let's modify the palindrome.py file you created in the previous step.

  1. Open the palindrome.py file in your VS Code editor.

  2. Modify the content of the palindrome.py file 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)}")

In this modified code:

  • Inside the is_palindrome(lst) function, we create a reversed copy of the input list lst using slicing lst[::-1] and store it in the reversed_lst variable.
  • We then compare the original list lst with the reversed list reversed_lst using the equality operator ==.
  • The function returns True if the original list is equal to the reversed list (i.e., it's a palindrome) and False otherwise.

To run the script, execute the following command in the terminal:

python ~/project/palindrome.py

You should see the same output as in the previous step:

[1, 2, 3, 2, 1] is a palindrome: True
[1, 2, 3, 4, 5] is a palindrome: False

This output confirms that list1 is a palindrome, and list2 is not, using the explicit reversal method. This approach makes the logic more explicit and easier to understand.

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.

  1. Open the palindrome.py file in your VS Code editor.

  2. 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.

Summary

In this lab, you learned how to identify list palindromes in Python, which are lists that read the same forwards and backward. You created a palindrome.py script containing an is_palindrome(lst) function that uses slicing (lst[::-1]) to efficiently reverse a list and compare it to the original, returning True if it's a palindrome and False otherwise.

The script was tested with two example lists, list1 (a palindrome) and list2 (not a palindrome), and the output confirmed the function's ability to correctly identify palindromes. The lab also introduced the concept of explicitly reversing the list for comparison, although the provided content was truncated.