-1

I have two examples below. Why does Example 1 return duplicate values? I am expecting both code snippets to return [[4], [4, 3], [4, 3, 2], [4, 3, 2, 1]]

Ex 1:

def Example1(arr):
   listToInput = []
   result = []
   for i in range(len(arr) - 1, -1, -1):
       listToInput.append(arr[i])
       result.append(listToInput)
   return result 

Ex 2:

def Example2(arr):
   listToInput = []
   result = []
   for i in range(len(arr) - 1, -1, -1):
       listToInput.append(arr[i])
       result.append(list(listToInput))
   return result 
print(Example1([1,2,3,4])) # Output is [[4, 3, 2, 1], [4, 3, 2, 1], [4, 3, 2, 1], [4, 3, 2, 1]]
print(Example2([1,2,3,4])) # Output is [[4], [4, 3], [4, 3, 2], [4, 3, 2, 1]]
ML_201721
  • 3
  • 2
  • Welcome to Stack Overflow. I see that you already know one way to make a copy, but the linked duplicate also explains why it is necessary. – Karl Knechtel Sep 21 '22 at 18:15

1 Answers1

2

In the first you're repeatedly appending the same list object. In the second, by sending your list to list you're creating a copy.

A simple example to demonstrate:

>>> foo = [1,2,3]
>>> bar = foo
>>> id(foo)
140390885806024
>>> id(bar)
140390885806024
>>> baz = list(foo)
>>> id(baz)
140390885839048

You may wish to use a list comprehension to replace your loops.

def example3(arr):
  n = len(arr)
  return [[arr[j] for j in range(n-1, i-2, -1)] for i in range(n, 0, -1)]
Chris
  • 26,361
  • 5
  • 21
  • 42