'Emptying a list after returning it in a recursive function

I've written the following code for outputting a series of integers in form of a list given a starting integer and total number of integers to be appended into the list. The starting integer will be incremented or decremented to get the next numbers. The direction of this change will alternate whenever starting integer is a multiple of 5. The function works correctly but if I call the function more than once then the subsequent lists include elements of the previous lists. In simple words, the function doesn't start from an empty list after first implementation.

def number_series(start, n, lst=[], l=0, c=0):
    if l == n:
        return lst
    lst.append(start)
    if start != 0:
        if start % 5 == 0:
            c += 1
    if c % 2 != 0:
        start = start - 1
    if c % 2 == 0:
        start = start + 1
    return number_series(start, n, lst, l+1, c)

How do I make the function start with an empty list everytime it is called?



Solution 1:[1]

lst=[] in definition doesn't create new list when you run function again but it creates this list only once - when you start script - and later it uses reference to this list - so next time it uses reference to list with previous elements.

So it works similar to

temp_lst = []   # create only once

def number_series(start, n, lst=temp_lst, l=0, c=0):
    # ... code ...

Don't use lst=[] but lst=None and inside function do if not lst: lst = []

def number_series(start, n, lst=None, l=0, c=0):
    if not lst: 
        lst = []
    # ... code ...

The same is for dictionary and for any more complex object.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1