I'm learning python arrays and I'm having trouble solving this code
a = [1,2,3,4,5]
b = [6,7,8,9,10]
a = b
print(a)
print(b)
I want to change the value of array b to be the same as the value of array a. like this:
a = [1,2,3,4,5]
b = [1,2,3,4,5]
but the result is like this:
a = [6,7,8,9,10]
b = [6,7,8,9,10]
what I want is the value of a is equal to b not vice versa. can you help me to solve this?
CodePudding user response:
you are assigning in the different order. You would like to assign list b to the value a not the other way around. But as lists are mutable, I would suggest doing
b = a.copy()
Otherwise you would modify b when you modify a.
CodePudding user response:
If you want your output, you can also try: b = a
CodePudding user response:
If I am getting you correctly you can use:
b = a.copy() # as mentioned in other comments
#or
b = a[:]
This way the value of a will be assigned to b. At the same time if you change any of them the other one will not change.