Python - Given a list of integers that represents a decimal value, increment the last element by 1

When it is required to increment the last element by 1 when a decimal value is given an input, a method named ‘increment_num’ is defined that checks to see if the last element in the list is less than 9. Depending on this, operations are performed on the elements of the list.


Below is a demonstration of the same

def increment_num(my_list, n):

   i = n

   if(my_list[i] < 9):

      my_list[i] = my_list[i] + 1

   my_list[i] = 0
   i -= 1

   increment_num(my_list, i)

n = 4

my_list = [0, 1, 4, 7, 9]
print("The list is :")
increment_num(my_list, n)

if(my_list[0] > 0):
   print(my_list[0], ", ")
print("After incrementing, the list is :")


The list is :
[0, 1, 4, 7, 9]
After incrementing, the list is :
[0, 1, 4, 8, 0]


  • A method named ‘increment_num’ is defined that takes the list, and a number as parameters.

  • The last element in the list is checked to be less than 9.

  • If yes, the last element is incremented by 1, and is returned as output.

  • Otherwise, if the last element is 0, the index is decremented by 1, and the ‘increment_num’ method is called again.

  • Outside the function, the value of ‘n’, and the list are defined.

  • They are displayed on the console.

  • The method is called by passing the required parameters.

  • The output is displayed on the console.

Updated on: 20-Sep-2021


Kickstart Your Career

Get certified by completing the course

Get Started