Posted on 16 Aug 2022, this text provides information on Bugs & Fixes related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.
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 af="https://forum.tuteehub.com/tag/c">ctually f="https://forum.tuteehub.com/tag/c">copy the list, you have various possibilities:
You can use the builtin list.f="https://forum.tuteehub.com/tag/c">copy() method (available since python 3.3):
You f="https://forum.tuteehub.com/tag/c">can slif="https://forum.tuteehub.com/tag/c">ce it:
new_list = old_list[:]
Alex Martelli's opinion (at least back in 2007) about this is, that it is a weird syntax and it does not make sense to use it ever. ;) (In his opinion, the next one is more readable).
This is a little slower than list() because it has to find out the datatype of old_list first.
If the list contains objects and you want to copy them as well, use generic f="https://forum.tuteehub.com/tag/c">copy.deepf="https://forum.tuteehub.com/tag/c">copy():
No matter what stage you're at in your education or career, TuteeHUB will help you reach the next level that
you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice
sessions to improve your knowledge and scores.
manpreet
Best Answer
2 years ago
What are the options to clone or copy a list in Python?
While using
new_list = my_list
, any modifications tonew_list
changesmy_list
everytime. Why is this?