0

I made a program:

k = int(input())
n = int(input())
row = []
arr = []
quantity = 0

for i in range(k):
    row.append(1)

for i1 in range(k ** k):
    arr.append(row)
    for i in range(len(row)):
        if row[i] + 1 <= k:
            row[i] += 1
            break
        else:
            row[i] = 1
print(arr)

And when I run it, i can see something strange in output:

[[1,1],[1,1],[1,1],[1,1]]

Why is it so?

NNJunior
  • 27
  • 5
  • `arr.append(row)` is appending additional references to one and the same row. – John Coleman Oct 25 '19 at 16:48
  • That post answers the reason behind this one Essentially you're adding `row` (the *same object*) multiple times, and keep modifying it. Eventually you just print the current state of `row` four times. You might want to do `arr.append(row.copy())`, which would fix this. – Green Cloak Guy Oct 25 '19 at 16:48
  • 2
    Possible duplicate of [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – John Coleman Oct 25 '19 at 16:48

1 Answers1

0

This is working fine

    k = int(input())
    n = int(input())
    row = []
    arr = []
    quantity = 0

    for i in range(k):
        row.append(1)

    for i1 in range(k ** k):
        arr.append(row[::])

        for i in range(len(row)):
            if row[i] + 1 <= k:
                row[i] += 1
                break
            else:
                row[i] = 1
    print(arr)
Pritish kumar
  • 512
  • 6
  • 13