-1

Im a little new to python, so this question may be very easy to answer. However, the logic doesnt make sense to me which is why I am posting this question. While there have been similar questions asked, they all used large chunks of code that were hard to read. Here is the program in python:

list1 = [1,2,3,4,5]

list2 = list1

for i in range(len(list2)):
    list2[i] += 1

print list1

When I run this program, it returns list1 as [2,3,4,5,6], which is identical to list2. My question is why list1 is connected to list2, and how to keep them independent of each other. Thank you for answering.

jwodder
  • 54,758
  • 12
  • 108
  • 124
Shawn
  • 3
  • 3

2 Answers2

1

When you do list2 = list1, you are just passing the reference of list1 to list2 , you instead need to make copy of list1 and pass that copy to list2 . Example -

list1 = [1,2,3,4,5]

list2 = list1[:]

for i in range(len(list2)):
    list2[i] += 1

print list1
>> [1, 2, 3, 4, 5]

Or You can also use copy module -

>>> import copy
>>> list1 = [1,2,3,4,5]
>>> list2 = copy.copy(list1)
>>> for i in range(len(list2)):
...     list2[i] += 1
...
>>> list1
[1, 2, 3, 4, 5]

If the list contains objects and you may want to copy them as well, in that case use copy.deepcopy()

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
0

By default assignment operator in python links the two objects, i.e. creates binding between the two objects. in order for you to create a new independent object and still copy the original. you would have to use copy ( shallow or deep , depending on your requirement )

list2 = copy.copy(list1)
bhavin
  • 122
  • 7