PythonLists and tuples
list. copy()
Returns a shallow copy of a list.
- Returns
- A new list with the same items.
- Changes the original
- No
Example
#Python
original = ["HTML", "CSS"]
alias = original
copy = original.copy()
alias.append("JS")
copy.append("Python")
print(original)
print(copy)Resultsaved result, you can check it
['HTML', 'CSS', 'JS']
['HTML', 'CSS', 'Python']
Definition and usage
#The copy() method creates a new list with the same items. Changes to the copy (adding or removing items) do not affect the original.
A plain assignment b = a does not copy the list. Both variables then point to the same object, and a change through one is visible through the other.
The copy is shallow: nested lists and dictionaries are shared between both lists. For a full, deep copy, use copy.deepcopy().
Syntax
#Syntax
list.copy()More examples
#Python
import copy
board = [[0, 0], [0, 0]]
shallow = board.copy()
deep = copy.deepcopy(board)
shallow[0][0] = 1
print(board)
print(deep)Resultsaved result, you can check it
[[1, 0], [0, 0]]
[[0, 0], [0, 0]]
Good practices
#- Equivalent ways to make a shallow copy are
my_list[:]andlist(my_list). - For lists of lists or lists of dictionaries, reach for
copy.deepcopy().
Related entries
#Spotted a mistake or missing an example? Write to us.