Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

While executing the below code: 

new_list = my_list

If I make any changes in my_list, it will also make the changes in the new_list. How can I make copy the list to prevent it?

1 Answer

0 votes
by (108k points)

With the code that you have provided, that is:

 new_list = my_list, 

You are not having two lists. The task of the '='(assignment operator in Python) is just to copy the reference to the list, not the actual list, so both new_list and my_list refer to the same list after the assignment.

To actually copy the list, you can refer to the below code:

new_list = old_list.copy()

Browse Categories

...