0

I have this code

def array_combos(n,k):

    arCombos = []
    i = 0
    a = [0]*k

    while i > -1:
        for j in range(i+1, k):
            a[j] = a[j-1]+1
        i=j
        print(a)
        arCombos.append(a)
        while a[i] == i + n - k:
            i -= 1
        a[i] += 1

    return arCombos

The print(a) print right values but list that function return is popolate by one single array n times. If I use yield insted of popolate list function work perfectly. Can we help? Tks

azro
  • 53,056
  • 7
  • 34
  • 70
user9846973
  • 57
  • 2
  • 8
  • 1
    Add shallow copies, printing works since you are printing snapshots: `arCombos.append(a[:])`. Otherwise you keep adding references to the *same* list object. – user2390182 May 07 '21 at 09:43

1 Answers1

1

The arCombos.append(a) always append the same, and only, instance of a, so you save it to the main arCombos multiple times, but there is still one instance that keep being modified.

Pass a copy of it with code like, more at Get a copy of list

arCombos.append(a[:])
arCombos.append(list(a))
azro
  • 53,056
  • 7
  • 34
  • 70