what is the difference between del a[:] and a = [] when I want to empty a list called a in python? [duplicate]

There is a difference, and it has to do with whether that list is referenced from multiple places/names.

>>> a = [1, 2, 3]
>>> b = a
>>> del a[:]
>>> print(b)
[]

>>> a = [1, 2, 3]
>>> b = a
>>> a = []
>>> print(b)
[1, 2, 3]

Using del a[:] clears the existing list, which means anywhere it’s referenced will become an empty list.

Using a = [] sets a to point to a new empty list, which means that other places the original list is referenced will remain non-empty.

The key to understanding here is to realize that when you assign something to a variable, it just makes that name point to a thing. Things can have multiple names, and changing what a name points to doesn’t change the thing itself.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)