Reputation: 11
I am trying to recursively remove items with same value from the list. It is partially works, but when it reaches to return, it still executed else statement after it and returns None. I am interested to accomplish this recursively.
def remove_from_list(item, lst):
if item not in lst:
return (item, lst)
else:
lst.remove(item)
nw = lst[:]
remove_from_list(item, nw)
lst = [7, 6, 5, 4, 3, 4, 5, 41]
remove_from_list(6, lst)
Any clues why this is happening?
Upvotes: 0
Views: 39
Reputation: 135
If you return the value returned by the recursive call, your function will return the modified list instead of None:
def remove_from_list(item, lst):
if item not in lst:
return (item, lst)
else:
lst.remove(item)
nw = lst[:]
return remove_from_list(item, nw)
A bit of explanation:
In python, every function returns None when the end of the function is reached. I've modified your code to make this easier to understand:
def remove_from_list(item, lst):
if item not in lst:
return (item, lst)
else:
lst.remove(item)
nw = lst[:]
remove_from_list(item, nw)
return None
Here, the result of the call remove_from_list(item, nw)
is neither stored, nor returned, so it is 'lost', and python continues to the return None
statement.
Upvotes: 2