I wonder why if I split a string with multiple characters into a list, then del
function works only if I save the list into a new object?
Example:
x = 'Hello world'
del x.split()[0]
print(x)
out: Hello world
y = x.split()
del y[0]
print(y)
out: ['world']
First, x.split()
creates a list that is entirely independent of x
(even ignoring the fact that str
values are immutable); modifying that list won't affect x
in any way.
Second, you didn't save a reference to the list returned by x.split()
, so even though del x.split()[0]
does mutate that list, once the statement completes, the entire list is subject to garbage collection.
In your second example, you do have a reference t the return value of x.split(0)
, so you can observe the result of del
.