Reputation: 169
In the following python code, I have a list i.e. to_do_list
of two lists i.e. other_events
and grocery_list
where I inserted an item in grocery_list
and then deleted it.
My confusion is, when I updated grocery_list
, to_do_list
is automatically updated but when I deleted grocery_list
, to_do_list
is not updated... why?
grocery_list = ['banana', 'mango', 'apple']
other_events =['pick up kids','do laundry', 'dance class']
to_do_list = [other_events, grocery_list]
print(to_do_list)
grocery_list.insert(1,'onions');
print(grocery_list)
del grocery_list
print(to_do_list)
its output is:
[['pick up kids', 'do laundry', 'dance class'], ['banana', 'mango', 'apple']]
['banana', 'onions', 'mango', 'apple']
[['pick up kids', 'do laundry', 'dance class'], ['banana', 'onions', 'mango', 'apple']]
Upvotes: 0
Views: 63
Reputation: 466
use del grocery_list[:]
instead
ouput :
[['pick up kids', 'do laundry', 'dance class'], ['banana', 'mango', 'apple']]
['banana', 'onions', 'mango', 'apple']
[['pick up kids', 'do laundry', 'dance class'], []]
but why ?
assume we have a list :
grocery_list = ['banana', 'mango', 'apple']
del grocery_list
grocery_list
when you use this to delete list program raise an error :
Traceback (most recent call last):
File "<pyshell#619>", line 1, in <module>
del grocery_list
NameError: name 'grocery_list' is not defined
in this code you used del grocery_list
which only delete grocery_list
(Deletion of a name removes the binding of that name from the local or global namespace) and don't clear the list you must use del grocery_list[:]
to compeletely delete it
for more detail for del
ref to this
Upvotes: 1
Reputation: 1189
grocery_list has many references to it and the
del grocery_list
will only remove one reference while other references will exists.
One way to remove all the references from a list is to use slice assignment
del grocery_list[:]
Upvotes: -1
Reputation: 111
The reason why, when you update grocery_list
your object to_do_list
is updated is that your list to_do_list
contain a only reference on grocery_list
.
Now, why after deleting grocery_list
, to_do_list
is not updated is that the keywork del
doesn't delete the object on which but only delete grocery_list
from the namespace.
Here is a quote from the Python Language Reference on what del
does :
Deletion of a name removes the binding of that name from the local or global namespace
Upvotes: 1