-1

I wanted to modify an array but keeping an original version of it so I coded:

a = ["a","b","c","d","e","f"]
b = a
a.append("g")

I expected:

a = ["a","b","c","d","e","f","g"]
b = ["a","b","c","d","e","f"]

But I retrieved:

a = ["a","b","c","d","e","f","g"]
b = ["a","b","c","d","e","f","g"]

It does not matter if I append a value to a or b, I get the same result.

limi
  • 1

1 Answers1

0
a = ["a","b","c","d","e","f"]
b = []
b.extend(a)
print (b)
a.append("g")
print(a)

Output:

['a', 'b', 'c', 'd', 'e', 'f']

['a', 'b', 'c', 'd', 'e', 'f', 'g']

PSR
  • 249
  • 1
  • 10
  • "b = a" does not do what you think, only a reference is copied. You can either use list.extend() or list.copy(). They both get the job done – PSR Jan 21 '22 at 08:27
  • Caveat: If you have a nested list like `a = [[0], [1], [2]]` and copy with `extend` you might run into problems. After `a[0].append("g")` you'll get `[[0, 'g'], [1], [2]]` for `b`. – Matthias Jan 21 '22 at 09:13
  • understood. But OP did not specify nature of the list. OP has posted a regular list – PSR Jan 21 '22 at 09:32