Palindromes in Word Lists with Python

"Every small algorithm is a reflection: it shows both the logic of the machine and the creativity of the one who writes it."

Palindromes are words or phrases that read the same from left to right and right to left, such as "oso", "radar", or "reconocer".
In programming, working with word lists and checking which ones are palindromes is a very useful exercise to practice conditionals, loops, and list comprehensions in Python.

In this guide, you’ll learn how to detect palindromes in a word list with Python, with easy-to-follow examples and reusable code.

What is a palindrome in a word list?

When we have a list in Python like:

words = ["radar", "oso", "python", "reconocer", "java"]

The goal is to go through each word and check if it meets the condition of being a palindrome. The expected result would be:

["radar", "oso", "reconocer"]

How to detect palindromes in word lists

The basic logic consists of:

  1. Taking each word from the list.
  2. Comparing it with its reversed version ([::-1]).
  3. Keeping those that are the same.

Simple example in Python

words = ["radar", "oso", "python", "reconocer", "java"]

palindromes = [w for w in words if w == w[::-1]]

print(palindromes)

Output:

['radar', 'oso', 'reconocer']

Using functions for clarity

We can create a function is_palindrome() to reuse across different projects:

def is_palindrome(word: str) -> bool:
    return word == word[::-1]

words = ["oro", "casa", "oso", "perro", "ana"]

palindromes = [w for w in words if is_palindrome(w)]
print(palindromes)

Output:

['oro', 'oso', 'ana']

Practical example with user input

words = input("Enter words separated by spaces: ").split()

palindromes = [w for w in words if w == w[::-1]]

print("Palindromes found:", palindromes)

Example input:

oso casa radar luna reconocer

Output:

Palindromes found: ['oso', 'radar', 'reconocer']
  1. Modify the code to ignore case sensitivity ("Oso" should also be detected as a palindrome).
  2. Make the program display the total number of palindromes found.
  3. Work with complete phrases and remove spaces before checking.

Detecting palindromes in word lists with Python is an excellent practice to improve your skills in string manipulation, loops, and list comprehensions. This concept can also be extended to larger projects, such as text filters, string validators, or linguistic data analysis.

You may also be interested in: