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
🌐
Programiz
programiz.com › python-programming › methods › built-in › reversed
Python reversed()
The reversed() function returns an iterator object that provides access to the elements of an iterable (list, tuple, string, etc.) in reverse order. string = 'Python' result = reversed(string) # convert the iterator to list and print it print(list(result)) # Output: ['n', 'o', 'h', 't', 'y', 'P']
🌐
W3Schools
w3schools.com › python › python_howto_reverse_string.asp
How to reverse a String in Python
There is no built-in function to reverse a String in Python. The fastest (and easiest?) way is to use a slice that steps backwards, -1.
Discussions

Is there a way to reverse a function in python? - Stack Overflow
I'm writing a program that takes a string and turns it into what looks like a random sequence of characters but can be turned back into the original string later. I have a function that does this, ... More on stackoverflow.com
🌐 stackoverflow.com
How to make a function do reverse of its job Python - Stack Overflow
How do you make a function do reverse of what it was programmed to do in Python without reprogramming the entire function? For example: swap1 = "abc" swap2 = "def" def swap(): global swap1, sw... More on stackoverflow.com
🌐 stackoverflow.com
write a python program to reverse the given numbers - Stack Overflow
Find centralized, trusted content ... you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... n=int(input("Enter number :")) rev=0 while(n>0): dig = n rev=rev*10+dig n=n//10 print("The reverse of the number:" ,rev) ... a = input("Enter : ") x = [num for num in a] # Getting the individual digits b = reversed(x) # reversed() is a built in function ... 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
July 7, 2024
People also ask

How to reverse a string in Python without a reverse function?
You can reverse a string in Python using slicing: reversed_string = original_string[::-1].
🌐
guvi.in
guvi.in › blog › python › python reverse string: 7 effective ways with examples
Python Reverse String: 7 Effective Ways with Examples
What is a reversed function in Python?
The reversed() The function in Python returns an iterator that accesses the given sequence in the reverse order. It works with sequences like lists, tuples, and strings.
🌐
guvi.in
guvi.in › blog › python › python reverse string: 7 effective ways with examples
Python Reverse String: 7 Effective Ways with Examples
What is the reverse of True in Python?
In Python, reverse=True an argument is used with sorting functions like sorted() and list.sort(). It sorts the elements in descending order.
🌐
guvi.in
guvi.in › blog › python › python reverse string: 7 effective ways with examples
Python Reverse String: 7 Effective Ways with Examples
🌐
Programiz
programiz.com › python-programming › examples › reverse-a-number
Python Program to Reverse a Number
Python range() Function · To understand this example, you should have the knowledge of the following Python programming topics: Python for Loop · Python while Loop · num = 1234 reversed_num = 0 while num != 0: digit = num % 10 reversed_num = reversed_num * 10 + digit num //= 10 print("Reversed Number: " + str(reversed_num)) Output · 4321 · In this program, while loop is used to reverse a number as given in the following steps: First, the remainder of the num divided by 10 is stored in the variable digit.
🌐
W3Schools
w3schools.com › python › ref_func_reversed.asp
Python reversed() Function
Python Overview Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods Python File Methods Python Keywords Python Exceptions Python Glossary · Built-in Modules Random Module Requests Module Statistics Module Math Module cMath Module · Remove List Duplicates Reverse a String Add Two Numbers
🌐
GUVI
guvi.in › blog › python › python reverse string: 7 effective ways with examples
Python Reverse String: 7 Effective Ways with Examples
January 8, 2026 - If you’re inclined towards a functional programming approach in Python, the reduce() function from the functools The module is a powerful tool you can utilize. Unlike other methods, reduce() takes a function and an iterable and applies the function cumulatively to the items of the iterable from left to right, reducing the iterable to a single value. This characteristic can be cleverly used to reverse strings.
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.
Find elsewhere
🌐
Medium
medium.com › @khasnobis.sanjit890 › python-reverse-string-74cc521cf8ca
Python Reverse String. Today we are going to write some code… | by Sanjit Khasnobis | Medium
September 10, 2023 - def reverseStr_reversed_method(inputStr): inputStrlist = list(inputStr) outputStrlist = reversed(inputStrlist) outputStr = "".join(outputStrlist) return outputStr ... Here, we have used python inbuilt framework reversed method.
🌐
Toppr
toppr.com › guides › python-guide › references › methods-and-functions › methods › built-in › reversed › python-reversed
Python reversed(): reversed() Parameters, Return value from reversed()
July 29, 2021 - In python, we can retrieve the reverse of a number, a string, a list, and so on. The python reverse() function returns the sequence's reversed order.
🌐
Real Python
realpython.com › reverse-string-python
Reverse Strings in Python: reversed(), Slicing, and More – Real Python
July 31, 2023 - These features allow you to use slicing to directly generate a copy of a given string in reverse order. The second option is to use the built-in function reversed() to create an iterator that yields the characters of an input string in reverse order.
🌐
Tutorial Gateway
tutorialgateway.org › python-program-to-reverse-a-number
Python Program to Reverse a Number
April 7, 2025 - Within this program, When it reaches the rev = rev_Integer (num) line in the program, the compiler immediately jumps to the below function: ... The last line ends with a return Reverse statement.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-reversed-function
Python reversed() Method - GeeksforGeeks
February 17, 2026 - 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.
🌐
W3Schools
w3schools.com › python › ref_list_reverse.asp
Python List reverse() Method
The reverse() method reverses the sorting order of the elements. ... The built-in function reversed() returns a reversed iterator object. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-program-to-reverse-a-number
Python Program to Reverse a Number - GeeksforGeeks
November 18, 2025 - This method reverses the number by converting it to a string, slicing it in reverse order and converting it back to an integer. ... This method extracts digits from the end of the number using % 10 and builds the reversed number digit-by-digit.
🌐
Real Python
realpython.com › ref › builtin-functions › reversed
reversed() | Python’s Built-in Functions – Real Python
In your class, .__iter__() provides support for normal iteration, and .__reversed__() supports reverse iteration. ... In this step-by-step tutorial, you'll learn about Python's tools and techniques to work with lists in reverse order.
🌐
DataCamp
datacamp.com › tutorial › python-reverse-list
Python Reverse List: How to Reorder Your Data | DataCamp
February 27, 2025 - Solution: Use the reversed() function, which returns an iterator without creating a new list in memory. This is especially useful if you only need to iterate over the list in reverse without storing it. #Python reversed() to save memory with large lists large_list = range(1000000) for item ...
🌐
BeginnersBook
beginnersbook.com › 2018 › 06 › python-program-reverse-string
Python Program to Reverse a given String
Here we have defined a function and in the function we are reversing a string using for loop. The steps are as follows: Step 1: Create a loop to read each character of the String one by one. Step 2: Declare an empty String. Step 3: Concatenate the read character at the beginning of the string.
🌐
Educative
educative.io › answers › how-to-use-reverse-in-python
How to use reverse() in Python
The reversed() function takes any sequence as an argument and returns a reversed iterator object. The iterator object accesses the objects of the sequence in reverse order.