Reversing Strings

How to Use reversed() in Python

Python's reversed() returns a reverse iterator without copying the string. Learn how to use it, join the result, and compare it with C++ std::reverse.

On this page
  1. The short answer
  2. What reversed() returns
  3. Slicing as the other common way
  4. The C++ comparison
  5. Notes for C++ learners

The short answer

reversed() is a built-in Python function that gives you the items of a sequence in reverse order. It does not build a reversed string on its own, so for a string you join the characters back together:

text = "hello"
backward = "".join(reversed(text))
print(backward)  # olleh

reversed() works on sequences such as strings, lists, and tuples.

What reversed() returns

Calling reversed(text) returns a reversed iterator. It walks the sequence from the last item to the first, one item at a time. The reversed string only exists after you collect those items, which is what "".join() does here.

print(list(reversed("hello")))  # ['o', 'l', 'l', 'e', 'h']

Slicing as the other common way

Python also has slicing, and text[::-1] returns "olleh" in one step. Slicing is shorter, while reversed() makes the direction of the walk explicit, which can help when the code is read later.

The C++ comparison

Python strings are immutable, so Python always produces a new string. A C++ std::string can be changed, so the closest match to a Python reversal is std::reverse:

#include <algorithm>
#include <iostream>
#include <string>

int main() {
    std::string text = "hello";
    std::reverse(text.begin(), text.end());
    std::cout << text << "\n";  // olleh
}

To make a reversed copy and keep the original, C++ uses reverse iterators:

std::string backward(text.rbegin(), text.rend());

Python’s "".join(reversed(text)) and this constructor both produce a reversed copy.

Notes for C++ learners

Python 3 strings hold Unicode code points, so reversed() steps through code points rather than bytes. A std::string in C++ holds bytes, so the same reversal can split multi-byte UTF-8 characters apart. For that reason, check the text’s encoding before reversing it byte by byte in C++.

The complete guide to reversing strings

How to Reverse a String in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

Inheritance in C++

A practical guide to inheritance in C++: the syntax, access specifiers, constructor order, virtual functions and common mistakes, with short code examples.

Inheritance 7 min read

SOLID Principles in C++

Learn the five SOLID principles in C++ with short examples of single responsibility, open/closed, Liskov, interface segregation and dependency inversion.