ZetCode

Python reverse

last modified November 18, 2026 Python 3.15

In this article we show how to reverse lists, strings, and other sequences in Python.

When we reverse items, we change their order so that the last item comes first. Reversing should not be confused with sorting in descending order; a reversed list keeps the relative order of the original, only backwards.

Python has three main tools for reversing:

The reversed built-in calls the object's __reversed__ method when it is defined; otherwise it falls back to the sequence protocol (__len__ and __getitem__).

Reverse a list in place

The reverse method of a list reverses its elements in place.

reverse_list.py
nums = [2, 7, 8, 9, 1, 0]

res = nums.reverse()
print(nums)
print(res)

The method modifies the original list and returns None. A common mistake is to write nums = nums.reverse(), which replaces the list with None. Since no copy is made, the method needs no extra memory.

$ python reverse_list.py
[0, 1, 9, 8, 7, 2]
None

Reverse with slicing

The [::-1] slice works on every built-in sequence: lists, strings, tuples, bytes, and ranges. It returns a new, reversed object.

slicing.py
nums = [2, 7, 8, 9, 1, 0]
word = 'forest'
point = (3, 4, 5)
data = b'\x01\x02\x03'

print(nums[::-1])
print(word[::-1])
print(point[::-1])
print(data[::-1])

print(nums)
print(nums[::-2])

The slice has empty start and stop and a step of -1, so it walks the whole sequence from the end to the beginning. The original list is not modified. A step of -2 takes every second element, starting from the last.

$ python slicing.py
[0, 1, 9, 8, 7, 2]
tserof
(5, 4, 3)
b'\x03\x02\x01'
[2, 7, 8, 9, 1, 0]
[0, 9, 7]

The reversed function

The reversed built-in function returns a reverse iterator. It does not copy the data; it produces the elements one by one as we ask for them.

reversed_fun.py
words = ['forest', 'wood', 'sky', 'rock']

it = reversed(words)
print(it)

for word in it:
    print(word)

print(list(it))

for e in reversed(range(1, 10, 2)):
    print(e, end=' ')

print()
print(reversed(range(1, 10, 2)))

We loop over a reversed list and a reversed range.

for word in it:
    print(word)

print(list(it))

An iterator can be consumed only once. After the loop, the iterator is exhausted and list(it) returns an empty list. We call reversed again if we need a second pass.

print(reversed(range(1, 10, 2)))

Reversing a range gives a range_iterator; no list is created, which makes reversed(range(n)) cheap even for huge ranges. The memory addresses in the output differ between runs.

$ python reversed_fun.py
<list_reverseiterator object at 0x7cda6986fc10>
rock
sky
wood
forest
[]
9 7 5 3 1 
<range_iterator object at 0x7cda699abab0>

Reversing dictionaries and sets

Dictionaries keep insertion order, and since Python 3.8 they and their views can be reversed. Sets have no order and cannot be reversed.

reversed_types.py
capitals = {'Slovakia': 'Bratislava', 'Hungary': 'Budapest',
            'Poland': 'Warsaw'}

for country in reversed(capitals):
    print(country)

for country, city in reversed(capitals.items()):
    print(f'{country}: {city}')

colours = {'red', 'green', 'blue'}

try:
    reversed(colours)
except TypeError as e:
    print(e)

print(sorted(colours, reverse=True))

Reversing a dictionary yields its keys from the last inserted to the first. The items, keys, and values views are reversible too. For a set, reversed raises a TypeError; to get a predictable order, we sort the set with sorted, here in descending order.

$ python reversed_types.py
Poland
Hungary
Slovakia
Poland: Warsaw
Hungary: Budapest
Slovakia: Bratislava
'set' object is not reversible
['red', 'green', 'blue']

Reverse a string

Strings are immutable and have no reverse method. We create a new reversed string with slicing, or by joining the characters from reversed.

reverse_string.py
import unicodedata

word = 'forest'

print(word[::-1])
print(''.join(reversed(word)))

text = unicodedata.normalize('NFD', 'café')
print(len(text), text[::-1])

text = unicodedata.normalize('NFC', text)
print(len(text), text[::-1])

Both approaches reverse code points, not user-perceived characters. This matters for text with combining characters.

text = unicodedata.normalize('NFD', 'café')
print(len(text), text[::-1])

In the decomposed (NFD) form, the letter é is stored as a plain e followed by a combining acute accent, so the string has five code points. After reversing, the accent comes first and no longer sits on the e. Normalizing to the composed form (NFC) first gives a single code point for é and the expected result. Emoji sequences and some scripts have the same problem; a grapheme-aware library is needed for them.

$ python reverse_string.py
tserof
tserof
5 ́efac
4 éfac

Reverse words

To reverse the order of words in a sentence, we split it into a list, reverse the list, and join it back.

reverse_words.py
sentence = 'an old falcon flew over the town'

words = sentence.split()
print(' '.join(reversed(words)))

print(' '.join(word[::-1] for word in words))

The first expression reverses the order of the words. The second keeps the order of the words but reverses each word with a generator expression.

$ python reverse_words.py
town the over flew falcon old an
na dlo noclaf welf revo eht nwot

Looping backwards with indexes

Sometimes we need both the index and the element while going backwards.

loop_back.py
words = ['forest', 'wood', 'sky', 'rock']

for i in range(len(words) - 1, -1, -1):
    print(i, words[i])

print('----------')

for i, word in reversed(list(enumerate(words))):
    print(i, word)

The first loop counts down with range(len(words) - 1, -1, -1); the stop value is -1 because the stop is exclusive. The second loop is easier to read: enumerate pairs the elements with their original indexes, and we reverse the pairs. The enumerate object is not a sequence, so we convert it to a list first.

$ python loop_back.py
3 rock
2 sky
1 wood
0 forest
----------
3 rock
2 sky
1 wood
0 forest

Reverse versus sorting in descending order

Reversing and sorting in descending order are different operations, although they can give the same result for sorted data.

sorted_reverse.py
vals = [3, 1, 4, 1, 5, 9, 2, 6]

print(vals[::-1])
print(sorted(vals, reverse=True))

users = [('John', 34), ('Lucy', 28), ('Paul', 34), ('Anna', 19)]

print(sorted(users, key=lambda u: u[1], reverse=True))
print(sorted(users, key=lambda u: u[1])[::-1])

vals[::-1] only flips the original order, while sorted(vals, reverse=True) sorts the values from the largest.

print(sorted(users, key=lambda u: u[1], reverse=True))
print(sorted(users, key=lambda u: u[1])[::-1])

The two expressions differ for equal keys. Python's sort is stable, and reverse=True keeps that property: John and Paul, both 34, stay in their original order. Reversing an ascending sort flips the equal elements as well.

$ python sorted_reverse.py
[6, 2, 9, 5, 1, 4, 1, 3]
[9, 6, 5, 4, 3, 2, 1, 1]
[('John', 34), ('Paul', 34), ('Lucy', 28), ('Anna', 19)]
[('Paul', 34), ('John', 34), ('Lucy', 28), ('Anna', 19)]

Reverse the digits of a number

Integers are not sequences. We can reverse their digits arithmetically, or convert the number to a string, reverse it, and convert it back.

reverse_number.py
def reverse_digits(n):

    rev = 0
    while n > 0:
        n, digit = divmod(n, 10)
        rev = rev * 10 + digit
    return rev


print(reverse_digits(12345))
print(int(str(12345)[::-1]))

print(reverse_digits(1200))

The divmod function returns the quotient and the remainder of the division by 10; the remainder is the last digit, which we append to the result. Trailing zeros of the original become leading zeros, which disappear: 1200 reversed is 21.

$ python reverse_number.py
54321
54321
21

Palindromes

A palindrome reads the same forwards and backwards. Reversing is the natural way to check for one.

palindromes.py
def is_palindrome(text):

    chars = [c.casefold() for c in text if c.isalnum()]
    return chars == chars[::-1]


phrases = ['radar', 'forest', 'A man, a plan, a canal: Panama',
           'Was it a car or a cat I saw?', 'Never odd or even.']

for phrase in phrases:
    print(f'{phrase!r}: {is_palindrome(phrase)}')

We keep only letters and digits and fold them with casefold, which is a stronger form of lower intended for caseless comparisons. Then we compare the list with its reversed copy.

$ python palindromes.py
'radar': True
'forest': False
'A man, a plan, a canal: Panama': True
'Was it a car or a cat I saw?': True
'Never odd or even.': True

The __reversed__ method

A class can define the __reversed__ special method to control how reversed works with its instances. The method should return a new iterator over the elements in reverse order.

reversed_magic.py
class Vowels:

    def __init__(self):
        self.vowels = ['a', 'e', 'i', 'o', 'u', 'y']

    def __iter__(self):
        return iter(self.vowels)

    def __reversed__(self):
        print('__reversed__ called')
        for idx in range(len(self.vowels) - 1, -1, -1):
            yield self.vowels[idx]


vowels = Vowels()

print(*vowels)
print(*reversed(vowels))

The Vowels class is iterable thanks to __iter__. Its __reversed__ method is a generator that walks the indexes backwards, so no reversed copy of the list is made. The print statement shows that reversed calls the method.

$ python reversed_magic.py
a e i o u y
__reversed__ called
y u o i e a

Reversing via the sequence protocol

If a class does not define __reversed__, the reversed function works with objects that implement __len__ and __getitem__ with integer indexes.

sequence_protocol.py
class Countdown:

    def __init__(self, start):
        self.start = start

    def __len__(self):
        return self.start

    def __getitem__(self, idx):
        if idx >= self.start:
            raise IndexError(idx)
        return self.start - idx


cd = Countdown(5)

print(list(cd))
print(list(reversed(cd)))


class Bag:

    def __iter__(self):
        return iter([1, 2, 3])


try:
    reversed(Bag())
except TypeError as e:
    print(e)

Countdown implements the sequence protocol, so reversed asks for its length and then fetches the items from the last index down to 0. The Bag class is iterable but has neither __reversed__ nor the sequence methods; an iterator can only go forward, so it cannot be reversed.

$ python sequence_protocol.py
[5, 4, 3, 2, 1]
[1, 2, 3, 4, 5]
'Bag' object is not reversible

Reverse a linked list

For linked data structures, we reverse the links between the nodes instead of moving the data.

linked_list.py
class Node:

    def __init__(self, value, next=None):
        self.value = value
        self.next = next


def reverse(head):

    prev = None
    while head:
        head.next, prev, head = prev, head, head.next
    return prev


def show(head):

    vals = []
    while head:
        vals.append(str(head.value))
        head = head.next
    print(' -> '.join(vals))


head = Node(1, Node(2, Node(3, Node(4))))
show(head)

head = reverse(head)
show(head)

The reverse function walks the list once and turns each next pointer around. The tuple assignment evaluates the right side first, so all three variables are updated with the old values. The function returns the new head, which was the last node.

$ python linked_list.py
1 -> 2 -> 3 -> 4
4 -> 3 -> 2 -> 1

Source

reversed – Python built-in functions

Mutable sequence types – Python documentation

In this article we have reversed lists, strings, dictionaries, numbers, and custom objects in Python. See also Python list slice, Python sort list, Python iterator, and Python string.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.