How does del operator work in list in python?

拟墨画扇 提交于 2019-12-01 15:49:06

l and c are bound to the same object. They both are references to a list, and manipulating that list object is visible through both references. del c unbinds c; it removes the reference to the list.

del l[::2] removes a specific set of indices from the list, you are now operating on the list object itself. You are not unbinding l, you are unbinding indices inside of the list.

You can compare this with retrieving and setting values as well. print c is different from print c[::2] and c = something is different from c[::2] = something; the first of both examples accesses just the list object, or assign a new value to c, the latter examples retrieve a slice of values or set new values to the sliced indices.

Under the hood, del c removes the name c from the dictionary handling all variables (globals() gives you a reference to this dictionary). del l[::2] calls the __delitem__ special method on the list, passing in a slice() object.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!