For working professionals
For fresh graduates
More
Reversing a number in Python can be a useful operation in many programming tasks. The challenge comes in choosing the right method to reverse the digits efficiently.
It’s a common task for beginners to grasp, but once you understand the basic concepts, it becomes a straightforward operation.
In this tutorial, you’ll learn about how the different methods work and when to use them.
Let’s dive in!
"Boost your Python skills with our Data Science and Machine Learning courses from top universities — take the next step in your learning journey today!"
The concept of reverse a number in Python using while loop is a great way to practice looping and number manipulation.
Here’s how we can reverse a number like 12345 using a while loop:
# initialize the number and set up the result variable
number = 12345
reversed_number = 0
#loop through each digit until the number becomes 0
while number > 0:
# Extract the last digit
digit = number % 10 # this gives us the last digit of the number
reversed_number = reversed_number * 10 + digit # shift the current reversed number by one place and add the digit
#remove the last digit from the original number
number = number // 10 # This reduces the number by removing the last digit
#print the reversed number
print("Reversed number:", reversed_number)
Output:
Reversed number: 54321
Explanation:
We start by setting the number we want to reverse, 12345, and initialize reversed_number to 0. This variable will store the reversed version as we process each digit.
The while loop continues as long as the number is greater than 0. Inside the loop, we extract the last digit of the number using the modulus operator %. For example, 12345 % 10 gives us the last digit, 5.
Once we have the last digit, we update reversed_number. To do this, we first multiply reversed_number by 10 (to shift its digits one place to the left) and then add the current digit to it. This ensures the new digit is added to the right of the previously reversed number. For example, after the first iteration, reversed_number becomes 5.
After extracting the last digit, we reduce the original number by dividing it by 10 (using integer division //). This removes the last digit, so in the first iteration, the number becomes 1234, then 123, and so on until it becomes 0.
Finally, once the loop ends (when the number becomes 0), we print the reversed number, which in this case will be 54321.
Key Takeaways:
"Kickstart your coding journey with our free Python courses, tailored just for you — master Python programming fundamentals, explore essential libraries, and work on practical case studies!"
The concept of reverse a number in Python for loop involves first converting the number into a string and then iterating over each digit in reverse order. This is an efficient way to reverse a number and gives you good practice with string manipulation.
Let’s reverse the number 6789 using a for loop:
# initialize the number
number = 6789
# convert the number to a string for easy iteration
str_number = str(number) # convert the number to a string
#initialize the reversed number variable
reversed_number = 0
#loop through each digit in reverse order
for digit in str_number:
#update the reversed number
reversed_number = reversed_number * 10 + int(digit) # multiply by 10 to shift and add the digit
# print the reversed number
print("Reversed number:", reversed_number)
Output:
Reversed number: 9876
Explanation:
We start with the number 6789 and initialize it as a number.
To easily iterate through each digit of the number, we convert it into a string using str(). This makes it easier to loop through each individual digit. After conversion, str_number becomes '6789'.
We initialize a variable reversed_number to 0. This will hold the reversed number as we process each digit.
We use a for loop to iterate through each character (digit) in str_number. Since str_number is a string, each iteration gives us a digit as a string, which we then convert back to an integer using int().
In each iteration of the loop, we multiply the current value of reversed_number by 10 (to shift the digits to the left) and add the current digit. This effectively builds the reversed number from right to left.
After the loop finishes, we print the reversed_number, which now holds the reversed value of the original number.
Key Takeaways:
Also Read: Python Program to Convert List to String
This method of reversing numbers using a for loop is useful when you prefer working with strings or need to apply additional string manipulation.
Recursion can be used to reverse a number in Python by repeatedly extracting the last digit and appending it to the result. The function calls itself with the remaining digits until the number becomes 0, at which point the recursion stops, and the reversed number is returned.
Let’s reverse the number 1234 using a recursive function.
# define the recursive function
def reverse_number(n, reversed_num=0):
#base case: When n becomes 0, return the reversed number
if n == 0:
return reversed_num
# extract the last digit and build the reversed number
digit = n % 10 # get the last digit
reversed_num = reversed_num * 10 + digit # add it to the reversed number
# recur with the remaining number
return reverse_number(n // 10, reversed_num)
# call the function with the original number
number = 1234
reversed_number = reverse_number(number)
print("Reversed number:", reversed_number)
Output:
Reversed number: 4321
Explanation:
We define a function reverse_number that takes two parameters: n (the number to reverse) and reversed_num (which will hold the reversed number). Initially, reversed_num is set to 0.
The base case is when n becomes 0. At this point, we return the reversed_num, which holds the reversed number.
We extract the last digit of n using the modulus operator (% 10). This gives us the rightmost digit of the number.
We update reversed_num by multiplying it by 10 (to shift the digits) and adding the extracted digit.
We call the reverse_number function recursively, passing the integer division of n by 10 (n // 10) to remove the last digit and continue the process until the base case is met.
We call the reverse_number function with 1234, and it returns 4321 after the recursion completes.
Key Takeaways:
Also Read: Recursive Feature Elimination: What It Is and Why It Matters?
In this approach, you convert the number to a string and use slicing to reverse the string. This method is both compact and intuitive, making it ideal for beginners and those who want a straightforward solution to reverse a number.
#convert the number to a string
number = 98765
str_number = str(number)
# use string slicing to reverse the string
reversed_str = str_number[::-1]
# convert the reversed string back to an integer
reversed_number = int(reversed_str)
# print the reversed number
print("Reversed number:", reversed_number)
Output:
Reversed number: 56789
Explanation:
First, we convert the number 98765 to a string using str(number). This allows us to manipulate the digits easily as characters.
The key here is using string slicing. The syntax [::-1] is a shorthand to reverse the string. It means:
So, str_number[::-1] reverses the string '98765' to '56789'.
After reversing the string, we convert it back to an integer using int(). This gives us the reversed number in its integer form.
Finally, we print the reversed number, which is 56789.
Key Takeaways:
Also Read: Different Ways of String formatting in Python: Top 3 Methods
Unlike other methods, reversed() works with any iterable, including strings and lists. To reverse a number using this method, we’ll first convert it to a string, reverse the string, and then convert it back to an integer.
# convert the number to a string
number = 8901
str_number = str(number)
# reverse the string using the reversed() method
reversed_str = ''.join(reversed(str_number))
# convert the reversed string back to an integer
reversed_number = int(reversed_str)
# print the reversed number
print("Reversed number:", reversed_number)
Output:
Reversed number: 1098
Explanation:
The first step is to convert the number 8901 into a string using str(number). This step is necessary because the reversed() method works only on iterable objects like strings or lists.
We apply the reversed() method to the string str_number. The reversed() function returns an iterator that produces the string's characters in reverse order. We then use ''.join()'' to join these characters back into a single string.
After reversing the string, we convert it back to an integer using int(). This gives us the reversed number.
Finally, we print the reversed number, which in this case is 1098.
Key Takeaways:
If you're looking for an alternative to string slicing, this method is a great option.
Reversing a number in Python using a list is a simple and effective approach that builds on the concept of manipulating a sequence of digits.
Let’s break this process into clear steps.
#convert the number into a string
number = 45891
str_number = str(number)
#convert the string into a list of characters (digits)
digit_list = list(str_number)
#reverse the list using slicing
reversed_list = digit_list[::-1]
#join the reversed list into a string
reversed_str = ''.join(reversed_list)
#convert the reversed string back to an integer
reversed_number = int(reversed_str)
#print the reversed number
print("Reversed number:", reversed_number)
Output:
Reversed number: 19854
Explanation:
The number 45891 is converted into a string using str(number). This allows you to treat each digit as an individual character.
Using the list() function, the string is broken down into a list of its individual digits: ['4', '5', '8', '9', '1'].
The slicing technique [::-1] reverses the order of elements in the list. The result is ['1', '9', '8', '5', '4'].
Using ''.join(reversed_list), the reversed list of digits is combined back into a single string: "19854".
Finally, the reversed string is converted back to an integer using int(). This ensures the output is a numeric value, not a string.
The print() statement outputs the reversed number, which is 19854.
Key Takeaways:
A stack in Python operates on the principle of Last In, First Out (LIFO), meaning the last element added is the first one removed.
Let’s look at this step-by-step.
#convert the number into a string
number = 34567
str_number = str(number)
#initialize an empty stack
stack = []
#push each digit of the number into the stack
for digit in str_number:
stack.append(digit)
#pop digits from the stack to form the reversed string
reversed_str = ''
while stack:
reversed_str += stack.pop()
#convert the reversed string back to an integer
reversed_number = int(reversed_str)
#print the reversed number
print("Reversed number:", reversed_number)
Output:
Reversed number: 76543
Explanation:
The number 34567 is converted into a string using str(number), so each digit can be processed individually.
We use a Python list (stack = []) as a stack. Lists in Python allow us to mimic stack operations like push (append) and pop.
Using a for loop, each digit from the string str_number is added to the stack with stack.append(digit). The stack now looks like this: ['3', '4', '5', '6', '7'].
Using a while loop, we repeatedly remove the top digit from the stack with stack.pop() and add it to reversed_str. The LIFO nature of the stack ensures the digits are retrieved in reverse order. The final reversed string is "76543".
The reversed string is converted back to a number using int(reversed_str), ensuring the output is a numeric value.
The print() statement outputs the reversed number, which is 76543.
Key Takeaways:
Try implementing this yourself! Stacks are a fundamental data structure in computer science, and this exercise is a great way to understand their practical application.
Also Read: How to Implement Stacks in Data Structure? Stack Operations Explained
You can reverse a number in Python using a for loop by converting the number to a string, iterating over the digits in reverse order, and then converting the reversed sequence back to an integer.
The simplest way is to use a for loop combined with slicing or the reversed() function to iterate through the digits in reverse and construct the reversed number.
Yes, you can reverse a number in Python using a while loop by extracting the digits one by one using modulus (%) and division (//) until the number becomes zero, and then constructing the reversed number.
It depends on your preference and use case. If you prefer to work with strings, reverse a number in Python using a for loop is easier. For numeric operations, reversing a number in Python using a while loop is more straightforward.
Yes, when using a for loop, you need to convert the number to a string because a for loop iterates over sequences like strings or lists.
You can reverse a number in Python using a while loop by performing arithmetic operations to extract and rearrange the digits without converting to a string.
Python automatically removes leading zeros in integers. For example, reversing 120 will give 21 instead of 021.
Yes, you can handle negative numbers by first converting the number to a string, excluding the negative sign, reversing the digits, and reapplying the negative sign to the result.
Yes, but you would treat it as a string. Reverse the digits, including the decimal point, and then convert it back to a floating-point number if needed.
Learning this technique enhances your understanding of loops, string manipulation, and number processing, which are essential skills in Python programming.
Yes, you can use a list comprehension to reverse the digits of a number by converting it into a string, iterating in reverse, and then converting it back to an integer. However, this is more commonly done with a for loop or slicing.
Ready to challenge yourself? Take our Free Python Quiz!
Pavan Vadapalli
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.