0

I have a list a and set it to [1, 2, 3, 4, 5]. Then I set b to a. My goal is to make two seperate versions of a, aka, I want b to change while a dosen't change. However, when I remove 5 from b, a becomes, [1, 2, 3, 4], exactly the same as b! My code is shown below:

a = [1, 2, 3, 4, 5]
b = a
b.remove(5)
print(b, a)

Here is my output:

[1, 2, 3, 4] [1, 2, 3, 4]

How can I achieve my goal?

CoderCookie10
  • 81
  • 1
  • 10

3 Answers3

1

To make a copy of a, you can use:

b = a[:]

This question has been asked already.

1

or you can take part of the list:

a = [1,2,3,4,5]
b = a[:4]
print(a,b)
dimay
  • 2,768
  • 1
  • 13
  • 22
Naaman
  • 62
  • 3
1

You can use the following code without changing the original list


a = [1,2,3,4,5]
b = a.copy()