Answer the question
In order to leave comments, you need to log in
How to remove the last element of a list using recursion?
Please describe the course of action. As I understand it, first we must check the number of elements in the list, if it is more than one, we run through the entire list to the very end and assign the value "None" to the last element. (If I'm wrong about something, I'll be glad to hear corrections). This function is implemented in Python.
def destruct_last(list):
if len(list) == 1:
return None
Answer the question
In order to leave comments, you need to log in
https://docs.python.org/3/tutorial/datastructures.html
Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)
How to remove the last element of a list using recursion?
The function needs a parameter for the current position with a default value of 0:
The function itself needs to check if we are on the last element of the list (pos == len(lst)-1).
If we are, then we change the value of the element to None.
Otherwise, we call the function recursively, passing it the same list and as position -- pos+1
a = [1, 1, 1, 1, 1]
def destr_array(array):
if len(array) > 1:
array.pop(-1)
destr_array(array)
destr_array(a)
print(a)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question