pragya.go pragya.go - 1 month ago 7
Python Question

confusion in python printing the lists

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']]

Answer Source

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