Program - Creating copies of mutable objects


Topic: Program - Creating copies of mutable objects

Solution

my_list1 = [[1, 2, 3]] * 2
print('initially ---> ', my_list1)
my_list1[1][0] = 'a'
print("after my_list1[1][0] = 'a' ---> ", my_list1)
my_list2 = [[1, 2, 3] for i in range(2)]
print('initially:  ---> ', my_list2)
my_list2[1][0] = 'a'
print("after my_list2[1][0] = 'a':  ---> ", my_list2)
for a, b in zip(my_list1, my_list2):
    print('id my_list1: {}, id my_list2: {}'.format(id(a), id(b)))



List all Python Programs