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.

Below is a demonstration of the same −

Example

 Live Demo

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)

Output

The list is :
[51645, 24567, 36743, 89452, 2122]
The value of K is
3
The result is :
[645, 567, 743, 452, 122]

Explanation

  • A list is defined and displayed on the console.

  • The value for K is defined and is displayed on the console.

  • A list comprehension is used to iterate over the list, and integer 10 is raised to power of K.

  • Every element is divided by the above operation’s result, and remained is stored in a list.

  • This result is assigned to a variable.

  • This is the output that is displayed on the console.

Updated on: 06-Sep-2021

114 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements