View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

How to Reverse a Number in Python

Updated on 21/01/20255,536 Views

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!"

How to Reverse a Number in Python Using While Loop

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:

  1. Initialize the number and the result variable:

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.

  1. Looping through the digits:

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.

  1. Building the reversed number:

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.

  1. Removing the last digit:

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.

  1. Printing the reversed number:

Finally, once the loop ends (when the number becomes 0), we print the reversed number, which in this case will be 54321.

Key Takeaways:

  • The while loop is an effective choice to reverse a number in Python using while loop because it allows you to perform repetitive tasks until a specific condition is met.
  • Modulus (%) is used to extract the last digit of a number.
  • Integer division (//) removes the last digit from the number, reducing it to the next digit.

"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!"

How to Reverse a Number in Python Using For Loop

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:

  1. Initialize the number:

We start with the number 6789 and initialize it as a number.

  1. Convert the number to a string:

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'.

  1. Initialize the reversed number:

We initialize a variable reversed_number to 0. This will hold the reversed number as we process each digit.

  1. Loop through 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().

  1. Update the reversed number:

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.

  1. Printing the reversed number:

After the loop finishes, we print the reversed_number, which now holds the reversed value of the original number.

Key Takeaways:

  • For loops provide a clean way to iterate through a string representation of a number, making the logic straightforward when reversing numbers.
  • Int conversion ensures we can work with numeric values while updating the reversed number.
  • String conversion allows us to treat the digits of a number as individual elements, making it easier to manipulate and reverse the number.

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.

Reverse a Number in Python Using Recursion

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:

  1. Define the recursive function:

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.

  1. Base case:

The base case is when n becomes 0. At this point, we return the reversed_num, which holds the reversed number.

  1. Extract the last digit:

We extract the last digit of n using the modulus operator (% 10). This gives us the rightmost digit of the number.

  1. Build the reversed number:

We update reversed_num by multiplying it by 10 (to shift the digits) and adding the extracted digit.

  1. Recursive call:

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.

  1. Calling the function:

We call the reverse_number function with 1234, and it returns 4321 after the recursion completes.

Key Takeaways:

  • Recursion allows you to break down a problem into smaller subproblems. In this case, we repeatedly reverse the last digit and reduce the number.
  • The base case is crucial for stopping the recursion when the number becomes 0.
  • This method is elegant and compact, and you’ll see how recursion can be applied to many other problems as well.

Also Read: Recursive Feature Elimination: What It Is and Why It Matters?

How to Reverse a Number in Python Using String Slicing

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:

  1. Convert the number to a string:

First, we convert the number 98765 to a string using str(number). This allows us to manipulate the digits easily as characters.

  1. String slicing to reverse:

The key here is using string slicing. The syntax [::-1] is a shorthand to reverse the string. It means:

  • : refers to selecting the entire string.
  • -1 tells Python to step backwards, effectively reversing the string.

So, str_number[::-1] reverses the string '98765' to '56789'.

  1. Convert the reversed string back to an integer:

After reversing the string, we convert it back to an integer using int(). This gives us the reversed number in its integer form.

  1. Print the reversed number:

Finally, we print the reversed number, which is 56789.

Key Takeaways:

  • String slicing in Python is a concise and efficient way to reverse a string, and it can be applied to numbers by first converting them to strings.
  • The syntax [::-1] is easy to remember and is a quick method for reversing sequences in Python.
  • Converting the reversed string back to an integer is a simple step to restore the reversed number in numerical form.

Also Read: Different Ways of String formatting in Python: Top 3 Methods

How to Reverse a Number in Python Using the reversed() Method

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:

  1. Convert the number to a string:

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.

  1. Reverse the string using the reversed() method:

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.

  1. Convert the reversed string back to an integer:

After reversing the string, we convert it back to an integer using int(). This gives us the reversed number.

  1. Print the reversed number:

Finally, we print the reversed number, which in this case is 1098.

Key Takeaways:

  • The reversed() method provides a convenient way to reverse any iterable, including strings.
  • By combining reversed() with join(), you can reverse a number in Python in a clean and readable way.
  • This method is particularly useful when working with iterables, making it a flexible tool for various use cases.

If you're looking for an alternative to string slicing, this method is a great option.

How to Reverse a Number in Python Using a List

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:

  1. Convert the number into a string:

The number 45891 is converted into a string using str(number). This allows you to treat each digit as an individual character.

  1. Convert the string into a list of characters:

Using the list() function, the string is broken down into a list of its individual digits: ['4', '5', '8', '9', '1'].

  1. Reverse the list using slicing:

The slicing technique [::-1] reverses the order of elements in the list. The result is ['1', '9', '8', '5', '4'].

  1. Join the reversed list into a string:

Using ''.join(reversed_list), the reversed list of digits is combined back into a single string: "19854".

  1. Convert the reversed string back to an integer:

Finally, the reversed string is converted back to an integer using int(). This ensures the output is a numeric value, not a string.

  1. Print the reversed number:

The print() statement outputs the reversed number, which is 19854.

Key Takeaways:

  • This method leverages Python's ability to work seamlessly with strings and lists, making the process intuitive and efficient.
  • By using slicing ([::-1]), you can reverse the order of elements in a list or string effortlessly.
  • The approach is flexible and can be adapted for other applications involving sequences, such as reversing strings or lists in Python.

How to Reverse a Number in Python Using a Stack

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:

  1. Convert the number into a string:

The number 34567 is converted into a string using str(number), so each digit can be processed individually.

  1. Initialize an empty stack:

We use a Python list (stack = []) as a stack. Lists in Python allow us to mimic stack operations like push (append) and pop.

  1. Push each digit into the stack:

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'].

  1. Pop digits from the stack to form the reversed string:

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".

  1. Convert the reversed string back to an integer:

The reversed string is converted back to a number using int(reversed_str), ensuring the output is a numeric value.

  1. Print the reversed number:

The print() statement outputs the reversed number, which is 76543.

Key Takeaways:

  • A stack provides a structured way to reverse sequences, leveraging its LIFO property.
  • This method is particularly useful for learning how data structures like stacks can solve real-world problems.
  • By pushing and popping digits, you can reverse the number efficiently while gaining hands-on experience with stack operations.

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

FAQ's

1. How can I reverse a number in Python using a for loop?

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.

2. What is the simplest way to reverse a number in Python for loop?

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.

3. Can I reverse a number in Python using a while loop instead of a for loop?

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.

4. Which is better for reversing a number: a for loop or a while loop?

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.

5. Is it necessary to convert a number to a string to reverse it using a for loop?

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.

6. How do I reverse a number without converting it to a string in Python?

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.

7. What happens if the reversed number starts with zero?

Python automatically removes leading zeros in integers. For example, reversing 120 will give 21 instead of 021.

8. Can I reverse a negative number in Python using a for loop?

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.

9. Is it possible to reverse a floating-point number in Python?

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.

10. Why should I learn how to reverse a number in Python for loop?

Learning this technique enhances your understanding of loops, string manipulation, and number processing, which are essential skills in Python programming.

11. Can I use a list comprehension to reverse a number in Python?

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!

image
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

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.