{"id":817,"hash":"d6bfe488b733a96874040311dcaa6ed4f46c1ab3b187ff906c2690989bdded85","pattern":"How do I clone a list so that it doesn&#39;t change unexpectedly after assignment?","full_message":"While using new_list = my_list, any modifications to new_list changes my_list every time. Why is this, and how can I clone or copy the list to prevent it? For example:\n\n>>> my_list = [1, 2, 3]\n>>> new_list = my_list\n>>> new_list.append(4)\n>>> my_list\n[1, 2, 3, 4]","ecosystem":"pypi","package_name":"list","package_version":null,"solution":"new_list = my_list doesn't actually create a second list. 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.\n\nTo actually copy the list, you have several options:\n\nYou can use the built-in list.copy() method (available since Python 3.3):\n\nnew_list = old_list.copy()\n\nYou can slice it:\n\nnew_list = old_list[:]\n\nAlex 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).\n\nYou can use the built-in list() constructor:\n\nnew_list = list(old_list)\n\nYou can use generic copy.copy():\n\nimport copy\nnew_list = copy.copy(old_list)\n\nThis is a little slower than list() because it has to find out the datatype of old_list first.\n\nIf you need to copy the elements of the list as well, use generic copy.deepcopy():\n\nimport copy\nnew_list = copy.deepcopy(old_list)\n\nObviously the slowest and most memory-needing method, but sometimes unavoidable. This operates recursively; it will handle any number of levels of nested lists (or other containers).\n\nExample:\n\nimport copy\n\nclass Foo(object):\n    def __init__(self, val):\n         self.val = val\n\n    def __repr__(self):\n        return f'Foo({self.val!r})'\n\nfoo = Foo(1)\n\na = ['foo', foo]\nb = a.copy()\nc = a[:]\nd = list(a)\ne = copy.copy(a)\nf = copy.deepcopy(a)\n\n# edit orignal list and instance \na.append('baz')\nfoo.val = 5\n\nprint(f'original: {a}\\nlist.copy(): {b}\\nslice: {c}\\nlist(): {d}\\ncopy: {e}\\ndeepcopy: {f}')\n\nResult:\n\noriginal: ['foo', Foo(5), 'baz']\nlist.copy(): ['foo', Foo(5)]\nslice: ['foo', Foo(5)]\nlist(): ['foo', Foo(5)]\ncopy: ['foo', Foo(5)]\ndeepcopy: ['foo', Foo(1)]","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/2612802/how-do-i-clone-a-list-so-that-it-doesnt-change-unexpectedly-after-assignment","votes":3370,"created_at":"2026-04-19T04:51:46.372741+00:00","updated_at":"2026-04-19T04:51:46.372741+00:00"}