I
I
igoodmood2016-04-01 19:05:52
Python
igoodmood, 2016-04-01 19:05:52

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

4 answer(s)
S
sim3x, 2016-04-01
@sim3x

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.)

A
abcd0x00, 2016-04-02
@abcd0x00

How to remove the last element of a list using recursion?

You need to pass in each call a list, the current position and the length of the list. That is, the recursion should move the current position forward until it becomes less than the length by one.

A
Andrey Myvrenik, 2016-04-02
@gim0

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

O
Oleg Drozdov, 2016-04-04
@Ardarick

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)

I guess you can write shorter

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question