If you do this list_a = list_b, that'll copy a reference. That means: modifying one list also modifies the other. Example:
# -*- coding: utf-8 -*- # python list_a = [3, 4, 5] list_b = list_a list_a[0] = 7 print list_b # returns [7, 4, 5]
You can check by using the “id” function. The “id” returns the object's memory address.
# -*- coding: utf-8 -*- # python aa = [3, 4, 5] print id(aa) # sample output: 2129927212
# -*- coding: utf-8 -*- # python list_a = [3, 4, 5] list_b = list_a list_a[0] = 7 print id(list_a), id(list_b) # they have same id
You can use list_b = list_a[:]. When the first index are omitted, it means beginning of list. When the ending index is omitted, it means end of list. Here's a test:
# -*- coding: utf-8 -*- # python list_a = [3,4,5] list_b = list_a[:] print id(list_a) == id(list_b) # prints “false”. They are different objects print list_a == list_b # prints “true”.
# -*- coding: utf-8 -*- # python list_a = [3, 4, 5] list_b = [] list_b.extend(list_a) print id(list_a) == id(list_b) # prints “false” print list_a == list_b # prints “true”.
A even better way is using “list()”.
# -*- coding: utf-8 -*- # python list_a = [3, 4, 5] list_b = list(list_a) print id(list_a) == id(list_b) # prints “false” print list_a == list_b # prints “true”.
If you need to copy a nested list, you can use the module “copy”. Any of {slice, “.extend()”, “list()”} does not work. They only create a copy on the 0th level (called shallow copy). Elements of the list are copied by reference. Example:
# -*- coding: utf-8 -*- # python list_a = [[3, 4], [5, 6, [7, 8]]] list_b = list(list_a) list_a[0][1] = 9 print list_a # prints [[3, 9], [5, 6, [7, 8]]] print list_b # prints [[3, 9], [5, 6, [7, 8]]]
# -*- coding: utf-8 -*- # python import copy list_a = [[3, 4], [5, 6, [7, 8]]] list_b = copy.deepcopy(list_a) list_a[0][1] = 9 print list_a # prints [[3, 9], [5, 6, [7, 8]]] print list_b # prints [[3, 4], [5, 6, [7, 8]]]
See also: Python's Reference and Internal Model of Computing Languages.