Copy a list to another so that it does not change values when I modify the first list in Python

In this tutorial, we will learn how to Copy a list to another so that it does not change values when I modify the first list in Python.

list1=["apple","banana","grapes","mango","cheery"]

we have this list and we are going to copy it and assign it to the new list.

Code:

steps:

  1. 1st we will create a list “list1”
  2. Then we will copy this list and assign it to another list “list2”
  3. Now we will be modifying the 1st list “list1” and then we will check whether the 2nd list values changed or not.
#list1
list1=["apple","banana","grapes","mango","cheery"]
print("1st list: ",list1)

#copy list
list2=list1.copy()
print("copied list list2: ",list2)

#modifying the 1st list
list1.pop()

#Checking the values of both list after modification in 1st list
print("modified 1st list: ",list1)
print("after modification of 1st list list2 values: ",list2)

output:

1st list:  ['apple', 'banana', 'grapes', 'mango', 'cheery']
copied list list2:  ['apple', 'banana', 'grapes', 'mango', 'cheery']
modified 1st list:  ['apple', 'banana', 'grapes', 'mango']
after modification of 1st list list 2 values:  ['apple', 'banana', 'grapes', 'mango', 'cheery']

Here in the output, we saw that value of list2 is not changed after modifying the 1st list.

Explanation:

when we assigned a copied value of the main list to a new list then that new list won’t be affected while modifying or changing the main list because the new list act as a new variable that is independent.

Leave a Reply

Your email address will not be published.