Q:

Clear a list in a function each time it's run

I'm kind of new to programming. I'm trying to write an algorithm in python that gives all the prime factors of a number:
factors=[]
def factor(n):
    for i in range(2,n+1):
        if n%i==0:
            factors.append(i)
            factor(int(n/i))
            break
    return factors

It works, but whenever I run the 'factor' function again, it just appends to the already populated 'factors' list - how can I get the list to clear each time the function 'factor' is run?

A:

Declare a local variable inside the function. In your code you're actually modifying the global variable factors every time you call factor().
def factor(n, factors=None):
    factors = [] if factors is None else factors 
    for i in range(2, n + 1):
        if n%i==0 and i not in factors: #checks for duplicates as well
            factors.append(i)
            factor(int(n / i),factors) #pass the factors list in the recurive call
            break
    return factors

factor(20) #returns [2, 5]

