- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
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.
Example
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] > 0): print(my_list[0], ", ") print("After incrementing, the list is :") print(my_list)
Output
The list is : [0, 1, 4, 7, 9] After incrementing, the list is : [0, 1, 4, 8, 0]
Explanation
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.