So the question is to delete an element at position i in a list, what are the differences between the following actions?
i = 3
l = [0,1,2,3,4,5]
del l[i]
i = 3
l = [0,1,2,3,4,5]
l = l[:i] l[i 1:]
Both ways give the list the same result. But what are the essential differences? Why is the second operation not acceptable?
CodePudding user response:
But what are the essential differences?
The del
way modifies the list in place. This means that any other names for that list will have the change reflected:
i = 3
l = [0,1,2,3,4,5]
k = l
del l[i]
# k has changed
The id()
of the list does not change, because it is still the same list - only its contents have changed (just like if you used e.g. .append
or .pop
, or assigned to an element).
The slicing way creates a new list. This means that other names for the list will not have the change reflected - because they are still names for the original list, and that list was never changed.
i = 3
l = [0,1,2,3,4,5]
k = l
l = l[:i] l[i 1:]
# k has not changed
If there are no other names for the original list, then the slicing way allows for the original list to be garbage-collected. The new list will probably not have the same id()
as the original, because the old list's contents have to stick around during construction of the new one. There will be a temporary spike in the amount of memory used, which may matter for some programs with millions of elements in the list (or with elements that are very large objects).
If there are other names for the original list, then the new list will have a different id()
, because it is a different list and the original still exists.
CodePudding user response:
So the question is to delete an element at position
i
in a list
not
"to create another list without element i
". That's why the second operation is not acceptable