string(and tuple) in python is immutable,can not be modified in place

list is mutbale

spam = [0,1,2,3,4,5]
cheese = spam
cheese[1] = 'hello'
cheese
[0,'hello',2,3,4,5]
spam
[0,'hello',2,3,4,5]#spam is also changed as cheese, 
since list i stored in the refernce,cheese changed the refernce which also changed the spam

use copy module to recreate the same list to make change

import copy 
spam = [1,2,3,4,5]
cheese = copy.deepcopy(spam)
cheese[1] = 'hello'
cheese
[1,'hello',3,4,5]
spam
[1,2,3,4,5]  #in this way ,spam did not cchange since cheese copy a new list to change the index item

results matching ""

    No results matching ""