Copying a list

Lists and collections / Lists

import copy

numbers1 = [1, 2, 3, 4, 5]

# Assignment copies nothing: a second name
alias = numbers1

# Three ways to copy the elements
numbers2 = numbers1.copy()
numbers3 = list(numbers1)
numbers4 = numbers1[:]

numbers1[0] = 10

print(f'{numbers1 = }')
print(f'{alias = }')
print(f'{numbers2 = }')
print(f'{numbers3 = }')
print(f'{numbers4 = }')

# Nested lists: a copy shares the inner lists
matrix1 = [[1, 2], [3, 4]]
shallow = matrix1.copy()
deep = copy.deepcopy(matrix1)

matrix1[0][0] = 100

print(f'{shallow = }')
print(f'{deep = }')