Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python – Extract Rear K digits from Numbers
When it is required to extract rear K digits from numbers, a simple list comprehension, the modulo operator and the ** operator are used. The modulo operator with 10**K effectively extracts the last K digits from any number.
How It Works
The formula number % (10**K) extracts the rear K digits because:
-
10**Kcreates a number with K+1 digits (e.g., 10³ = 1000) - The modulo operation returns the remainder when dividing by this value
- This remainder is always less than
10**K, giving us exactly the last K digits
Example
Let's extract the last 3 digits from a list of numbers ?
my_list = [51645, 24567, 36743, 89452, 2122]
print("The list is :")
print(my_list)
K = 3
print("The value of K is")
print(K)
my_result = [element % (10 ** K) for element in my_list]
print("The result is :")
print(my_result)
The list is : [51645, 24567, 36743, 89452, 2122] The value of K is 3 The result is : [645, 567, 743, 452, 122]
Different Values of K
Here's how different K values affect the same number ?
number = 12345
for k in range(1, 6):
result = number % (10 ** k)
print(f"Last {k} digits of {number}: {result}")
Last 1 digits of 12345: 5 Last 2 digits of 12345: 45 Last 3 digits of 12345: 345 Last 4 digits of 12345: 2345 Last 5 digits of 12345: 12345
Using a Function
You can create a reusable function for this operation ?
def extract_rear_digits(numbers, k):
return [num % (10 ** k) for num in numbers]
# Test with different lists and K values
list1 = [12345, 67890, 111]
list2 = [987654, 123, 456789]
print("Extract last 2 digits:", extract_rear_digits(list1, 2))
print("Extract last 4 digits:", extract_rear_digits(list2, 4))
Extract last 2 digits: [45, 90, 11] Extract last 4 digits: [7654, 123, 6789]
Conclusion
Use the modulo operator with 10**K to extract the rear K digits from numbers. This method works efficiently with list comprehensions for processing multiple numbers at once.
Advertisements
