Python list element deletion question.

Asked 1 years ago, Updated 1 years ago, 129 views

a = ["Aa", "Bb", "Cc"]
b = ["11", "22", "33"]
c = []

a.extend(b)
c.append(a)
c.append(a)

print("1", c)

del a[3:]

print("2", c)

After using the del function in the above code, 11, 22, 33 of the list elements ['Aa', 'Bb', 'Cc', '11', '22', '33'], ['Aa', 'Bb', 'Cc', '11', '22', '33'] are deleted.

I think it is right that there should be no change in the c list, but I wonder why it is printed as ['Aa', 'Bb', 'Cc'], ['Aa', 'Bb', 'Cc'].

If it happens inevitably in the above code,

del... I wonder if there is a way to output ['Aa', 'Bb', 'Cc', '11', '22', '33'], ['Aa', 'Bb', 'Cc', '11', '22', '33'] after the function.

python python3.6

2022-09-21 22:06

1 Answers

It's a self-answer again...

If the original element is changed due to the reference of the list, it will be reflected immediately.

import copy

...

c = copy.deepcopy(c)

I solved it by adding it.


2022-09-21 22:06

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.