0

I want to take a value from a 2D array (so this value has a type of array) and assign it to a new variable. But when I make changes to this new variable, its original value in that 2D array also changes. I want to know if there is a correct way that I can do this?

Here is my example code.

a = [[1],[2],[3]]
b = a[1]
b.append(2)
a.append(b)
print(a)
print(b)

In the output, a, b will be

a = [[1], [2, 2], [3], [2, 2]]
b = [2, 2]

Where I don't want a[1] to be changed as well. If someone can help me figure this out? Thanks.

lyj
  • 23
  • 2

2 Answers2

0

This is probably one of the most confusing concept for beginner, when you are doing subscription slicing, b = a[1], the reference to first array a has been passed to b, which you whatever action you do to b, will be done to a[1]. unless you make a complete copy of the original array, any action to subscripted will lead to change in original, therefore, whenever you want to work with array without changing its initial value, copy it manually.

a = [[1],[2],[3]]
# in your case it is nested so it will be a bit intricate 
ac = list(map(lambda x:list(map(lambda y:y, x)), a))
b = ac[1]
b.append(2)
a.append(b)
print(a)
print(b)
# [[1], [2], [3], [2, 2]]
# [2, 2]
Weilory
  • 2,621
  • 19
  • 35
0

Because a[1] is an array, passing it to b will pass it by reference and not by value. You can use

b = a[1].copy()

to make a new instance of a[1] without effecting the original a[1].

A. Guy
  • 500
  • 1
  • 3
  • 10