Python reversed() — A Simple Guide with Video

Python’s built-in reversed(sequence) function returns a reverse iterator over the values of the given sequence such as a list, a tuple, or a string.

Python reversed()

Usage

Learn by example! Here are some examples of how to use the reversed() built-in function.

The most basic use is on a Python list:

>>> reversed([1, 2, 3])
<list_reverseiterator object at 0x0000017FB04EF8D0>

You can see that the return value of the reversed() function is not a list but an iterator object for efficiency reasons. There’s no reason to create a new reversed data structure just to go over a sequence in reverse order. Thus, if you want to create a new list or tuple of elements in reversed order, you need to convert the output to a list or tuple first using the list() or tuple() built-in functions.

>>> list(reversed([1, 2, 3]))
[3, 2, 1]
>>> tuple(reversed([1, 2, 3]))
(3, 2, 1)

You can also run the reversed() function on strings:

>>> print(*reversed('retxnif'))
f i n x t e r

This example makes use of the asterisk operator to unpack all elements in the reversed iterator into the print() function.

Syntax reversed()

You can use the reversed() method as follows:

Syntax:
reversed(sequence) -> new empty reversed iterator over sequence

Interactive Shell Exercise: Understanding reversed()

Consider the following interactive code:

Exercise: Guess the output before running the code.


Check out my new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Publisher Link: https://nostarch.com/pythononeliners


Performance Comparison of Ways to Reverse a List

There are many ways to reverse a list—all with linear runtime complexity in the number of elements. These are the primary methods to reverse a list:

  • list.reverse() — Best if you want to reverse the elements of list in place.
  • list[::-1] — Best if you want to write concise code to return a new list with reversed elements.
  • reversed(list) — Best if you want to iterate over all elements of a list in reversed order without changing the original list.

But, you may ask, what’s the most performant one?

Let’s run the reversed() method against different alternatives to reverse a list:

def reverse1():
    names = ['Alice', 'Bob', 'Carl', 'Dora']
    names.reverse()

def reverse2():
    names = ['Alice', 'Bob', 'Carl', 'Dora']
    names = names[::-1]

def reverse3():
    names = ['Alice', 'Bob', 'Carl', 'Dora']
    names = reversed(names)

def reverse4():
    names = ['Alice', 'Bob', 'Carl', 'Dora']
    l = []
    for i in range(len(names)-1, -1, -1):
        l.append(names[i])

def reverse5():
    names = ['Alice', 'Bob', 'Carl', 'Dora']
    l = []
    for i in range(1, len(names) + 1):
        l.append(names[-i])

import timeit
print('M1: ', timeit.timeit(reverse1, number=10000), '--> list.reverse()')
print('M2: ', timeit.timeit(reverse2, number=10000), '--> slicing')
print('M3: ', timeit.timeit(reverse3, number=10000), '--> reversed()')
print('M4: ', timeit.timeit(reverse4, number=10000), '--> loop')
print('M5: ', timeit.timeit(reverse5, number=10000), '--> loop + negative index')

The result is the following on my computer (Intel Core i7, 8th Gen, Python version 3.7):

M1:  0.0012140999999999957 --> list.reverse()
M2:  0.0016616999999999882 --> slicing
M3:  0.0019155999999999618 --> reversed()
M4:  0.005595399999999973 --> loop
M5:  0.006663499999999989 --> loop + negative index

It’s interesting to see that the least readable and least concise methods 4 and 5 are also slowest! Note that we didn’t convert the iterator returned by the reversed() method to a list—otherwise, it would have added a few milliseconds to the result.

Related Article: How to Reverse a List in Python?

Summary

Python’s built-in reversed(sequence) function returns a reverse iterator over the values of the given sequence such as a list, a tuple, or a string.

>>> list(reversed([1, 2, 3]))
[3, 2, 1]
>>> tuple(reversed([1, 2, 3]))
(3, 2, 1)

I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:


Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!