.

Python trick, sequence reversal

A small Python trick to reverse a a sequence is this:

>>> (1,2,3)[::-1]
(3, 2, 1)
>>> [1,2,3][::-1]
[3, 2, 1]
>>> 'reversed'[::-1]
'desrever'

The neat thing is it works by slicing the sequence with a negative step operator on any built-in 'sliceable' and returns the right data type as well. Equivalent code using reversed(), which returns an iterator, requires a bit more work in most cases:

>>> tuple(reversed((1,2,3)))
(3, 2, 1)
>>> list(reversed([1,2,3]))
[3, 2, 1]
>>> ''.join(reversed("reversed"))
'desrever'

Using this trick I created a simple function which tests if a string is palindromic:

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

>>> is_palindrome("sator arepo tenet opera rotas")
True
>>> is_palindrome("palindrome")
False
>>> is_palindrome("racecar")
True

posted on 29 Dec, 2008 to Python » view comments
blog comments powered by Disqus