⟵back

Python palindrome check

It's not uncommon to need to slice an iterable in Python. I found an interesting use case for it recently. I count myself lucky to have been born in a year that (at least for the past couple of millennia) only occurs once a century: a palindrome year. But how can I make people work a little to guess when that was? To answer this question, I wrote this:

from datetime import datetime

this_year = datetime.now().year

for year in range(this_year - 100, this_year):
    if str(year) == str(year)[::-1]:
        print(year)
        break

You'll notice that the slicing is a little interesting, as it's made up of three parts. What does it mean?

The basic syntax of slicing is as follows:

[start:stop:step]

Start and stop are pretty standard. The "start" index is where you start, the "stop" index is where you stop. And these default to 0, so you don't need to explicitly write 0. You can just leave it blank.

But what's "step"? It's actually always there, if somewhat invisible — it just has a default of 1, which means you're going forward in the iterable. If you set it to -1, however, it means that you're going over the iterable in reverse.

In this tiny program I wrote, we take the current year (2025) as the end of our range. The start of the range, 1925, is actually fairly arbitrary; it's just to make sure we don't go back a bit too far in time.

for year in range(this_year - 100, this_year):
    if str(year) == str(year)[::-1]:
        print(year)
        break

So starting from 1925, the program will iterate through all the years until it finds one that's exactly the same when reversed (year is cast as a string because it's not possible to do this check with integers). It will print the year and then stop the program so we don't venture off too far into the future and potentially print more than one year.