0

Let's see an example,

list1 = ["a", "b", "c"]
list2 = list1

then I append in list1

list1.append(1)
list1.append(2)
list1.append(3)

then list1 will look like

list1 = ["a", "b", "c", 1, 2, 3]

and list2 will also look like the same

list2 = ["a", "b", "c", 1, 2, 3]

this happens because python assign list by reference not by value. I want to prevent this, and I want after all this happens my both list looks like below:

list1 = ["a", "b", "c", 1, 2, 3]
list2 = ["a", "b", "c"]

How to do this?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Rezaul Karim Shaon
  • 145
  • 1
  • 2
  • 12

1 Answers1

1
list1 = ["a", "b", "c", 1, 2, 3]
list2 = list.copy()

This will work.

Rezaul Karim Shaon
  • 145
  • 1
  • 2
  • 12