Simply use list():
list1 = ['a', 'b', 'c', 'd']
# this will create a new list with a different mem ref
temp_list1 = list(list1)
for i in range(len(list1)):
temp_list1[i] = "1"
print list1; # ['a', 'b', 'c', 'd']
print temp_list1; # ['1', '1', '1', '1']
For nested lists you need to use deepcopy() from module copy.
Ene Uran
Posting Virtuoso
1,722 posts since Aug 2005
Reputation Points: 625
Solved Threads: 212
Here is an example for the use of deepcopy with a nested list. First without ...
# a nested list
list1 = ['a', 'b', 'c', 'd', [1, 2, 3]]
list2 = [x for x in list1]
# now replace 2 with 77 in list1
list1[4][1] = 77
print(list1) # ['a', 'b', 'c', 'd', [1, 77, 3]]
print(list2) # ['a', 'b', 'c', 'd', [1, 77, 3]] oops!!!
now with ...
import copy
# a nested list
list1 = ['a', 'b', 'c', 'd', [1, 2, 3]]
list2 = copy.deepcopy(list1)
# now replace 2 with 77 in list1
list1[4][1] = 77
print(list1) # ['a', 'b', 'c', 'd', [1, 77, 3]]
print(list2) # ['a', 'b', 'c', 'd', [1, 2, 3]] okay!!!
In the first example the list comprehension simply copied the inner list as an alias list which shares the memory reference.
vegaseat
DaniWeb's Hypocrite
5,976 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,416