1

I was working on a simple python project when I ran into an issue. I wanted to copy an array and something on to it but when I do that the original array also changes which is not what I want. I made a simple version of what my problem is with the desired output underneath. If anybody could help me with a fix that would be much appreciated.

array = [1]
x = range(5)

for i in x:
  array2 = array
  array2.append(1)
  print(array2)

#output
[1, 1]
[1, 1, 1]
[1, 1, 1, 1]
[1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1]

#desired output
[1, 1]
[1, 1]
[1, 1]
[1, 1]
[1, 1]
  • 1
    `array2 = array` -- they're not two different arrays. They're two names for the _same_ array (or, rather, the same list; arrays are something different -- see https://docs.python.org/3/library/array.html). – Charles Duffy Mar 31 '21 at 16:22

0 Answers0