

The Python 2 ways will also work in Python 3. There are different ways to do this in Python 2 and 3. If the objects contained themselves are mutable and one is changed, the change will be reflected in both lists. Shallow list copyĪ shallow copy only copies the list itself, which is a container of references to the objects in the list. A shallow copy creates a new list of the same objects, a deep copy creates a new list containing new equivalent objects. There are two semantic ways to copy a list.
#EXACT COPY FAST FULL#
In Python 2 and 3, you can get a shallow copy with a full slice of the original: a_copy = a_list In Python 3, a shallow copy can be made with: a_copy = a_py() What are the options to clone or copy a list in Python?

Print 'generator expression extend:', time()-t Print 'Custom Copy Only Copying Lists/Tuples/Dicts (no classes):', time()-t # values which aren't immutable (like lists, dicts etc) # Use the fast shallow dict copy() method and copy any This operates recursively it will handle any number of levels of nested lists (or other containers). Obviously the slowest and most memory-needing method, but sometimes unavoidable. If you need to copy the elements of the list as well, use generic epcopy(): import copy This is a little slower than list() because it has to find out the datatype of old_list first. You can use the built-in list() constructor: new_list = list(old_list) ) (In his opinion, the next one is more readable). You can use the built-in py() method (available since Python 3.3): new_list = old_py()Īlex 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. To actually copy the list, you have several options: 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.

New_list = my_list doesn't actually create a second list.
