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
990 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,770 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 15, 2020 in Python by Niroj
• 82,840 points
823 views
0 votes
0 answers
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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,464 views
0 votes
1 answer
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,770 points
2,416 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
9,288 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP