Python Reference ยท Lists, Tuples and Ranges
Python list.copy() method
Reference for Python list.copy(): make a shallow copy of a list, what shallow means for nested lists, and how it compares to slicing, list() and copy.deepcopy().
The copy() method returns a new list containing the same elements as the original. The two lists are separate objects: appending to or removing from one does not affect the other.
The copy is shallow. The new list holds references to the very same element objects, so if those elements are mutable, such as inner lists, a change made through one list is visible through the other.
a = [1, 2, 3] b = a.copy() b.append(4) print(a, b) # [1, 2, 3] [1, 2, 3, 4]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
list.copy()
This method takes no parameters.
Return value: a new list with the same items, in the same order.
Raises: nothing.
Usage notes
- Shallow, not deep. Only the outer list is duplicated. Nested lists, dicts or objects are shared. Use
copy.deepcopy(obj)when you need fully independent nested data. - Equal but not identical.
a.copy() == aisTrue,a.copy() is aisFalse. - Assignment does not copy.
b = acreates a second name for the same list. This is the most common source of "my original changed" bugs. - Equivalent spellings.
a[:],list(a)and[*a]give the same result.copy()is the most readable and, as a method, makes the intent obvious. - Immutable items are safe. A list of numbers, strings or tuples of those can be shallow-copied without surprises.
- Cost. Copying takes O(n) time and memory for the references, not for the objects they point at.
- Sorted copies.
sorted(a)returns a new sorted list without needingcopy(). Usea.copy()first only if you want to call an in-place method such assort()orreverse()safely. - Added in Python 3.3, matching
dict.copy()andset.copy().
Related
list.clear(),list.extend(),sorted(),list,dict.copy()- Lessons: Lists, Memory management