0

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?

Carsten
  • 2,765
  • 1
  • 13
  • 28

1 Answers1

1

You can't use *; use another list comprehension.

a = [a[0][:] for _ in range(3)] + a[1:]
chepner
  • 497,756
  • 71
  • 530
  • 681