Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is special about deleting an empty list?

Tags:

python

Consider the following...

In [1]: del []

In [2]: del {}
  File "<ipython-input-2-24ce3265f213>", line 1
SyntaxError: can't delete literal

In [3]: del ""
  File "<ipython-input-3-95fcb133aa75>", line 1
SyntaxError: can't delete literal

In [4]: del ["A"]
  File "<ipython-input-5-d41e712d0c77>", line 1
SyntaxError: can't delete literal

What is special about []? I would expect this to raise a SyntaxError too. Why doesn't it? I've observed this behavior in Python2 and Python3.

like image 490
Fredrick Brennan Avatar asked Jan 12 '13 23:01

Fredrick Brennan


1 Answers

The del statement syntax allows for a target_list, and that includes a list or tuple of variable names.

It is intended for deleting several names at once:

del [a, b, c]

which is the equivalent of:

del (a, b, c)

or

del a, b, c

But python does not enforce the list to actually have any elements.

The expression

del ()

on the other hand is a syntax error; () is seen as a literal empty tuple in that case.

like image 63
Martijn Pieters Avatar answered Oct 13 '22 02:10

Martijn Pieters