I have a deep list a=[[1, 2], 3]
for which I want to copy the first entry (the sublist) of the list multiple times to get [[1, 2], [1, 2], [1, 2], 3]
.
The following works:
a=[[1, 2], 3, 4]
for _ in range(2):
a = [a[0][:]] + a
print(a) # [[1, 2], [1, 2], [1, 2], 3, 4]
a[0][0] = 5
print(a) # [[5, 2], [1, 2], [1, 2], 3, 4]
When doing a list comprehension, I create only shallow copies:
a=[[1, 2], 3, 4]
a = [a[0][:]] * (3) + a[1:]
print(a) # [[1, 2], [1, 2], [1, 2], 3, 4]
a[0][0] = 5
print(a) # [[5, 2], [5, 2], [5, 2], 3, 4]
Question: How can I create deep copies of the sublist in a pythonic way?