List changes unexpectedly after assignment How do I clone or copy it to prevent this

0 votes
While using new_list = my_list, any modifications to new_list changes my_list everytime. Why is this, and how can I clone or copy the list to prevent it?
Dec 7, 2020 in Python by Roshni
• 10,480 points
90 views

1 answer to this question.

0 votes

With new_list = my_list, you don't actually have two lists. The assignment just copies 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 have various possibilities:

  • You can use the built-in list.copy() method (available since Python 3.3):

    new_list = old_list.copy()
    
  • You can slice it:

    new_list = old_list[:]
answered Dec 7, 2020 by Gitika
• 65,910 points

Related Questions In Python

0 votes
1 answer

How to clone or copy a list?

Hello @kartik, With new_list = my_list, you don't actually ...READ MORE

answered May 14, 2020 in Python by Niroj
• 82,760 points
233 views
0 votes
1 answer

How do I clone a Django model instance object and save it to the database?

Hello @kartik, Just change the primary key of ...READ MORE

answered Jun 22, 2020 in Python by Niroj
• 82,760 points
1,278 views
0 votes
1 answer
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 2,182 views
0 votes
0 answers
0 votes
1 answer

I want to download a file from the website by web scraping. Can anyone explain how to do this in jupyter lab (python) with an example?

Hey, Web scraping is a technique to automatically ...READ MORE

answered Apr 7, 2020 in Python by Gitika
• 65,910 points
719 views
0 votes
2 answers

How do I convert text file to CSV file with only plain python. Meaning no panda or any other special module?

Steps to Convert Text File to CSV ...READ MORE

answered Oct 15, 2020 in Python by Abdul Shekh
1,408 views