Copying Lists

  • This lesson explains how to create a copy of a list in Python using different techniques.

  • List Copy : 

    Copying a list means creating a new list that contains the same elements.

    If we don’t copy properly, changes in one list may affect the other.

    Daily Life Example

    Making a copy of:

    • Your homework notes

    • A photo duplicate

    • Backup of important files

Assignment (Reference to Same List)

Both change because they point to same memory.

list1 = [10, 20, 30]
list2 = list1   # NOT a copy
list2.append(40)
print(list1)

copy() Method

list1 = [1, 2, 3]
list2 = list1.copy()

list2.append(4)

print(list1)
print(list2)

Using list() Constructor

list1 = [5, 6, 7]
list2 = list(list1)   # creates a new copy of list1

list2.append(8)

print(list1)
print(list2)
 

Slicing Method

list1 = [10, 20, 30]
list2 = list1[:]   # creates a copy using slicing
list2.append(40)
print(list1)
print(list2)