0

What is the difference between these two methods;

# Solution 1
list1 = ['a', 'b', 'c', 'd']
temp_list1 = list1
for i in range(len(list1)):
    temp_list1[i] = "1"
print list1;              # ['1', '1', '1', '1']
print temp_list1;         # ['1', '1', '1', '1']

# Solution 2
list2 = ['a', 'b', 'c', 'd']
temp_list2 = list2
temp_list2 = ['1', '1', '1', '1']
print list2;              # ['a', 'b', 'c', 'd']
print temp_list2;         # ['1', '1', '1', '1']

By using solution1, want to update the temp_list1 with some other value at the same time want to retain the old value in list1. But this updated the both lists.

4
Contributors
4
Replies
6
Views
8 Years
Discussion Span
Last Post by vegaseat
0

Because your temporary list is the same thing as your other list. You said temp_list1 = list1 . This means that the value for temp_list1 will be the same address in memory as the value for list1, i.e. they reference the same thing. Modifying one modifies the other because they are just 2 different names for the same data.

0

I forgot to mention that in solution #2, you assign temp_list2 to the same address of memory as list2, but then that's undone as you create a new list (and new address in memory for it) consisting of four ones. Therefore, temp_list2 no longer refers to the same data as list2.

If you want to copy the list over without making the new name reference the same data, how about

list1 = ['a', 'b', 'c', 'd']
list2 = [x for x in list1]

That'll copy all the indices of list1 into a new address for list2, and thus, they are independent of each other.

1

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.

Votes + Comments
Well I learned something new about using list() :P
0

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.