No, this is not possible in Python (or most/any other languages). For any function that does slightly complicated branching or even common math operations, it is completely impossible to undo. One very simple example:

def foo(a, b):
    return a + b

foo.undo(6)  # made-up example syntax

What should this return? 0 and 6, or maybe -13 and 19? A reversible function needs to have an unambiguous mapping from both input to output and output to input. Anything in the function that would cause two different inputs to create the same output will break this mapping.

Especially in your example, you are utilizing randomness. How could the program even know what to undo if it is randomized? The mapping isn't even consistent for input to output, much less the other way around.

If you want to do something like this, you could use simple substitutions only (such as rot13), which provides a direct mapping between characters. You could also keep track of previous values in a dict with the function results being the keys, which would work because it is creating the mapping as it goes. This obviously would not work on its own across multiple runs of the program though, as it would not preserve the mapping.

Whichever method you choose, you will definitely need to write your own undo function.

Answer from Luke B on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_list_reverse.asp
Python List reverse() Method
Python Examples Python Compiler ... Bootcamp Python Certificate Python Training ... The reverse() method reverses the sorting order of the elements. ... The built-in function reversed() returns a reversed iterator ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-list-reverse
Python List Reverse() - GeeksforGeeks
April 25, 2025 - The reverse() method is an inbuilt method in Python that reverses the order of elements in a list.
Discussions

How do I reverse a string in Python? - Stack Overflow
In Python, strings are immutable. Changing a string does not modify the string. It creates a new one. Strings are sliceable. Slicing a string gives you a new string from one point in the string, backwards or forwards, to another point, by given increments. They take slice notation or a slice object in a subscript: ... While ''.join(reversed('foo')) is readable, it requires calling a string method, str.join, on another called function... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How do I reverse a list or loop over it backwards? - Stack Overflow
You know how python implements indexing. From right to left you have 0,1,2... and from left to right you have -1,-2,-3.. etc. To reverse a list, you cut it into two parts and you multiply the indexes on the right by their opposites on the left minus one. 2016-10-25T18:49:17.577Z+00:00 ... This solution is about 4.5k times slower than l[::-1], and at the same time much less legible. Functional ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Lazy Reverse Method in O(1) Time
There is reversed(list_object). More on reddit.com
๐ŸŒ r/Python
45
27
March 1, 2024
Why does [::1] reverse a string in Python?
On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: Limiting your involvement with Reddit, or Temporarily refraining from using Reddit Cancelling your subscription of Reddit Premium as a way to voice your protest. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
๐ŸŒ r/learnprogramming
15
12
September 21, 2023
Top answer
1 of 2
3

No, this is not possible in Python (or most/any other languages). For any function that does slightly complicated branching or even common math operations, it is completely impossible to undo. One very simple example:

def foo(a, b):
    return a + b

foo.undo(6)  # made-up example syntax

What should this return? 0 and 6, or maybe -13 and 19? A reversible function needs to have an unambiguous mapping from both input to output and output to input. Anything in the function that would cause two different inputs to create the same output will break this mapping.

Especially in your example, you are utilizing randomness. How could the program even know what to undo if it is randomized? The mapping isn't even consistent for input to output, much less the other way around.

If you want to do something like this, you could use simple substitutions only (such as rot13), which provides a direct mapping between characters. You could also keep track of previous values in a dict with the function results being the keys, which would work because it is creating the mapping as it goes. This obviously would not work on its own across multiple runs of the program though, as it would not preserve the mapping.

Whichever method you choose, you will definitely need to write your own undo function.

2 of 2
1

Many answers have pointed out how what you're describing (reversing the actions of a generic function) is mathematically impossible. I'll show you here a way you could accomplish this under some very specific circumstances, though I will hasten to point out that they are correct -- this will not work in the general case.

However, if you're frequently round-tripping these results, it might be helpful to memoize the results of your hash function and do a reverse lookup.

# This code assumes that the memo dictionary need not be bounded in size.
# A real implementation will likely include a method to cull old results
# once the memo reaches a certain size. See `functools.lru_cache` for a
# specific example of this made for speeding up repeated function calls.

_memo_dict = dict()

def hash(p):
    # produces strlist as above, then...

    _key = tuple(strlist)
    _memo_dict[_key] = p

def unhash(hashed_p: list[int]) -> str:
    cache_hit = _memo_dict.get(tuple(hashed_p))
    if cache_hit is not None:
        # we've previously hashed a string to get this
        # value so we can skip the calculations to reverse
        # the process and just hand back the result
        return cache_hit

    # otherwise, you should have some way to reverse it
    # manually here.
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ python โ€บ list-reverse-method
Python List reverse() Method: Syntax, Methods, and Examples
This built-in tool is part of how Python efficiently walks through a list backward. The underlying name comes from the behavior of a built-in reversed mechanism, which is powered by a built-in function.
๐ŸŒ
Real Python
realpython.com โ€บ ref โ€บ builtin-functions โ€บ reversed
reversed() | Pythonโ€™s Built-in Functions โ€“ Real Python
The built-in reversed() function takes a sequence as an argument and returns an iterator that yields the elements in reverse order.
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ library โ€บ functions.html
Built-in Functions โ€” Python 3.14.3 documentation
1 week ago - key specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). The default value is None (compare the elements directly). reverse is a boolean value.
Find elsewhere
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ python-reverse-list
Python Reverse List: How to Reorder Your Data | DataCamp
February 27, 2025 - The reversed() function in Python is an iterator that yields elements in reverse order without modifying the original list.
Top answer
1 of 14
3161

Using slicing:

>>> 'hello world'[::-1]
'dlrow olleh'

Slice notation takes the form [start:stop:step]. In this case, we omit the start and stop positions since we want the whole string. We also use step = -1, which means, "repeatedly step from right to left by 1 character".

2 of 14
329

What is the best way of implementing a reverse function for strings?

My own experience with this question is academic. However, if you're a pro looking for the quick answer, use a slice that steps by -1:

>>> 'a string'[::-1]
'gnirts a'

or more readably (but slower due to the method name lookups and the fact that join forms a list when given an iterator), str.join:

>>> ''.join(reversed('a string'))
'gnirts a'

or for readability and reusability, put the slice in a function

def reversed_string(a_string):
    return a_string[::-1]

and then:

>>> reversed_string('a_string')
'gnirts_a'

Longer explanation

If you're interested in the academic exposition, please keep reading.

There is no built-in reverse function in Python's str object.

Here is a couple of things about Python's strings you should know:

  1. In Python, strings are immutable. Changing a string does not modify the string. It creates a new one.

  2. Strings are sliceable. Slicing a string gives you a new string from one point in the string, backwards or forwards, to another point, by given increments. They take slice notation or a slice object in a subscript:

    string[subscript]
    

The subscript creates a slice by including a colon within the braces:

    string[start:stop:step]

To create a slice outside of the braces, you'll need to create a slice object:

    slice_obj = slice(start, stop, step)
    string[slice_obj]

A readable approach:

While ''.join(reversed('foo')) is readable, it requires calling a string method, str.join, on another called function, which can be rather relatively slow. Let's put this in a function - we'll come back to it:

def reverse_string_readable_answer(string):
    return ''.join(reversed(string))

Most performant approach:

Much faster is using a reverse slice:

'foo'[::-1]

But how can we make this more readable and understandable to someone less familiar with slices or the intent of the original author? Let's create a slice object outside of the subscript notation, give it a descriptive name, and pass it to the subscript notation.

start = stop = None
step = -1
reverse_slice = slice(start, stop, step)
'foo'[reverse_slice]

Implement as Function

To actually implement this as a function, I think it is semantically clear enough to simply use a descriptive name:

def reversed_string(a_string):
    return a_string[::-1]

And usage is simply:

reversed_string('foo')

What your teacher probably wants:

If you have an instructor, they probably want you to start with an empty string, and build up a new string from the old one. You can do this with pure syntax and literals using a while loop:

def reverse_a_string_slowly(a_string):
    new_string = ''
    index = len(a_string)
    while index:
        index -= 1                    # index = index - 1
        new_string += a_string[index] # new_string = new_string + character
    return new_string

This is theoretically bad because, remember, strings are immutable - so every time where it looks like you're appending a character onto your new_string, it's theoretically creating a new string every time! However, CPython knows how to optimize this in certain cases, of which this trivial case is one.

Best Practice

Theoretically better is to collect your substrings in a list, and join them later:

def reverse_a_string_more_slowly(a_string):
    new_strings = []
    index = len(a_string)
    while index:
        index -= 1                       
        new_strings.append(a_string[index])
    return ''.join(new_strings)

However, as we will see in the timings below for CPython, this actually takes longer, because CPython can optimize the string concatenation.

Timings

Here are the timings:

>>> a_string = 'amanaplanacanalpanama' * 10
>>> min(timeit.repeat(lambda: reverse_string_readable_answer(a_string)))
10.38789987564087
>>> min(timeit.repeat(lambda: reversed_string(a_string)))
0.6622700691223145
>>> min(timeit.repeat(lambda: reverse_a_string_slowly(a_string)))
25.756799936294556
>>> min(timeit.repeat(lambda: reverse_a_string_more_slowly(a_string)))
38.73570013046265

CPython optimizes string concatenation, whereas other implementations may not:

... do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b . This optimization is fragile even in CPython (it only works for some types) and isn't present at all in implementations that don't use refcounting. In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.

๐ŸŒ
Cherry Servers
cherryservers.com โ€บ home โ€บ blog โ€บ python โ€บ how to reverse a list in python (using 3 simple ways)
How to Reverse a List in Python (Using 3 Simple Ways) | Cherry Servers
November 7, 2025 - Pythonโ€™s reversed() function offers an easy method to reverse the elements of a list. Unlike other methods, reversed() doesn't make a new or changed list directly. Instead, it returns an iterator that can be used to go through the list in ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-reversing-list
Reversing a List in Python - GeeksforGeeks
Python's built-in reversed() function is another way to reverse the list.
Published ย  November 26, 2025
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-reversed-function
Python reversed() Method - GeeksforGeeks
3 weeks ago - reversed() function in Python returns an iterator that accesses elements in reverse order. It does not create a new reversed copy of the sequence, making it memory-efficient.
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ python-reverse-string
Python Reverse String - 5 Ways and the Best One | DigitalOcean
August 3, 2022 - However, there are various ways to reverse a string in Python. ... Using Slicing to create a reverse copy of the string. Using for loop and appending characters in reverse order ยท Using while loop to iterate string characters in reverse order and append them ยท Using string join() function with reversed() iterator
๐ŸŒ
Reddit
reddit.com โ€บ r/python โ€บ lazy reverse method in o(1) time
r/Python on Reddit: Lazy Reverse Method in O(1) Time
March 1, 2024 -

Why not make the list.reverse method in Python perform a lazy reverse? Instead of changing the underlying structure, it would adjust array operations so that [i] becomes [-i-1] and all iterations go backwards. This way, the list would appear reversed without actually modifying its structure.

The list would maintain this lazy reverse state for operations like insert, remove, index, iteration, and array access/editing. If an operation like + or .append is called, only then would the list be physically reversed.

In most programs, lists aren't typically appended to after being reversed. Implementing this could save time, making reversing an O(1) operation.

Note: Lazy reverse could be off by default, where you have to specify a parameter to be true to turn it on, or it could be a separate method.

๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ why does [::1] reverse a string in python?
r/learnprogramming on Reddit: Why does [::1] reverse a string in Python?
September 21, 2023 -

For example:

txt = "Hello World"[::-1]

Isn't the splice syntax [start : stop: step]? And default of start and stop are the beginning and end of the string? So that would make the above start at the beginning, stop at the end, but step by -1. That feels like it would start at the beginning, then step backwards to...before the beginning of the string?

Sorry for the silly question, I just can't figure out why this syntax works the way it does.

๐ŸŒ
Bhrighu
bhrighu.in โ€บ blog โ€บ reverse-a-string-in-python
How to Reverse a String in Python (5 Easy Methods)
Yes, Python has a built-in reversed() function that returns an iterator over a sequence in reverse order. It works on sequences like strings, lists, and tuples.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_func_reversed.asp
Python reversed() Function
Python Examples Python Compiler ... Bootcamp Python Certificate Python Training ... The reversed() function returns a reversed iterator object....
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ methods โ€บ built-in โ€บ reversed
Python reversed()
Become a certified Python programmer. Try Programiz PRO! ... The reversed() function returns an iterator object that provides access to the elements of an iterable (list, tuple, string, etc.) in reverse order.
๐ŸŒ
FavTutor
favtutor.com โ€บ blogs โ€บ reverse-list-python
Reverse Python List (9 Easy Ways) | FavTutor
March 30, 2022 - Learn what is a list and how to reverse a python list using 9 different methods. Also, understand how does list indexing works.