I want to know a better way to throw away all the elements on the list.

Asked 2 years ago, Updated 2 years ago, 136 views

mylist1 = [1,2,3]
mylist2 = mylist1

mylist2 = []

This clears the existing reference. What I want is that if you change mylist2, mylist1 will also be emptied, so I can't use that code.

I'm writing it like this now, but I don't think my code is Python-like (?), so I'd like to get help from others.

while len(alist) > 0 : alist.pop()

list python

2022-09-22 22:15

1 Answers

mylist1 = [1,2,3]
mylist2 = mylist1

mylist2 = []

This code does not replace the existing list, but allocates an empty list ([]) so the existing reference is erased.

If you want to modify the list, not assign it, please look down

From 3.3, clear() can be used in the list.

mylist1 = [1,2,3]
mylist2 = mylist1

Mylist2.clear() #mylist1 also changed

Change the existing list using slices

mylist1 = [1,2,3]
mylist2 = mylist1

del mylist2[:]

It functions like 2.

mylist1 = [1,2,3]
mylist2 = mylist1

mylist2[:] = []


2022-09-22 22:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.