简体   繁体   中英

confusion in python printing the lists

In the following python code, I have a list ie to_do_list of two lists ie 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']]

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

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

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[:]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM