'While I'm wrting a python code showing all the possible combinations of a list, I cannot clarify why expected results doesn't appear

I wanna write a code, which shows all the possible 'toPick' combinations of a list with length 'n'. Also, I want my function to be a recursive one. My code is here:

def pick(n, picked, toPick):
    if(toPick==0):
        print(picked)
        return picked[:-1]
    if(len(picked)==0):
        last = 0
    else:
        last = picked[-1]
    for next in range(last+1, n+1):
        picked.append(next)
        picked = pick(n, picked, toPick-1) # What happened here?

pick(5, [], 2)

My expected result is:

[1, 2]

[1, 3]

[4, 5]

but, the result shown on my window is:

[1, 2]

[1, 3]

[1, 4]

[1, 5]

Traceback (most recent call last):

...

AttributeError: 'NoneType' object has no attribute 'append'

So, I added some lines to detect the errors:

def pick(n, picked, toPick):
    if(toPick==0):
        print(picked)
        return picked[:-1]
    if(len(picked)==0):
        last = 0
    else:
        last = picked[-1]
    for next in range(last+1, n+1):
        picked.append(next)
        print("before pick:{}".format(picked)) # I wrote this line to track the error
        picked = pick(n, picked, toPick-1) # What happened here?
        print("after pick:{}".format(picked)) # I wrote this line to track the error

pick(5, [], 2)

but the result was:

before pick:[1]

before pick:[1, 2]

[1, 2]

after pick:[1]

before pick:[1, 3]

[1, 3]

after pick:[1]

before pick:[1, 4]

[1, 4]

after pick:[1]

before pick:[1, 5]

[1, 5]

after pick:[1]

after pick:None

Traceback (most recent call last):

...

AttributeError: 'NoneType' object has no attribute 'append'

Could you help me figure out what is wrong?



Sources

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

Source: Stack Overflow

Solution Source