1

This might have been asked before, but it's difficult to search for. Basically I am wondering how to make a copy of a list that will not be updated when the list changes. I have been tooling around in Python for a while now--surprised this is the first time I have come across this.

var = 10

varcopy = var

for i in range(0,5):
    var = var + i
    print var
    print varcopy

10
10
11
10
13
10
16
10
20


list = []


listcopy = list

for i in range(0,5):
    list.append(i)
    print list
    print listcopy


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

Why is the list copy ALSO being appended to?! How do I freeze it to get:

[0]
[]
[0, 1]
[]
[0, 1, 2]
[]
[0, 1, 2, 3]

etc...

Sam Weisenthal
  • 2,791
  • 9
  • 28
  • 66

1 Answers1

1

list and listcopy both refer to the same object. Here are some ways to make a copy of a list:

listcopy = list[:]

import copy
listcopy = copy.copy(list)

# Also make a copy of the objects in the list
import copy
listcopy = copy.deepcopy(list)
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173