Python copy list

Copying Lists in Python

In Python, a variable is simply a label or reference to an object in memory. Therefore, the assignment “lst1 = lst” refers to the same list object. Consider the following example:

lst = [10, 20]
print (“lst:”, lst, “id(lst):”, id(lst))
lst1 = lst
print (“lst1:”, lst1, “id(lst1):”, id(lst1))

This will produce the following output −

lst: [10, 20] id(lst): 1677677188288
lst1: [10, 20] id(lst1): 1677677188288

Therefore, if we update “lst”, it will automatically be reflected in “lst1”. Change lst[0] to 100

lst[0]=100
print ("lst:", lst, "id(lst):",id(lst))
print ("lst1:", lst1, "id(lst1):",id(lst1))

It will generate the following output −

lst: [100, 20] id(lst): 1677677188288
lst1: [100, 20] id(lst1): 1677677188288

Thus, we can say that “lst1” is not a physical copy of “lst”.

Using the copy() Method of the List Class

The Python list class has a copy() method that creates a new physical copy of a list object.

Syntax

lst1 = lst.copy()

The new list object will have a different id() value. The following example demonstrates this:

lst = [10, 20]
lst1 = lst.copy()
print (“lst:”, lst, “id(lst):”, id(lst))
print (“lst1:”, lst1, “id(lst1):”, id(lst1))

This produces the following output:

lst: [10, 20] id(lst): 1677678705472
lst1: [10, 20] id(lst1): 1677678706304

Even though the two lists have the same data, they have different id() values, so they are two different objects. “lst1” is a copy of “lst”. If we try to modify “lst”, it will not be reflected in “lst1”. See the example below −

lst[0]=100
print ("lst:", lst, "id(lst):",id(lst))
print ("lst1:", lst1, "id(lst1):",id(lst1))

It will produce the following output

lst: [100, 20] id(lst): 1677678705472
lst1: [10, 20] id(lst1): 1677678706304

Leave a Reply

Your email address will not be published. Required fields are marked *