- Trending Categories
- Data Structure
- Operating System
- MS Excel
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 return my_list[i] = 0 i -= 1 increment_num(my_list, i) n = 4 my_list = [0, 1, 4, 7, 9] print("The list is :") print(my_list) increment_num(my_list, n) if(my_list > 0): print(my_list, ", ") print("After incrementing, the list is :") print(my_list)
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.
Kickstart Your Career
Get certified by completing the courseGet Started