3

I have created a list in Python

>>> my_list = [1, 2, 3, 4]

Now if I want to delete the list, I would like to use the del operator like

>>> del my_list

This works fine and is probably the general way of using it. But somewhere I stumbled upon an unusual syntax

>>> del[my_list]

And this does the same thing! And now I am kind of confused how del actually works. I can understand the previous syntax with del being a built-in statement, but the second syntax looks like an indexing to me.

Himanshu Mishra
  • 8,510
  • 12
  • 37
  • 74

2 Answers2

10

del takes a target list of names, see the reference documentation:

del_stmt ::=  "del" target_list

Just like for assignments and for loops, a target list includes using [...] and (...) list and tuple syntax:

del (foo, bar)
del [spam, ham, eggs]

So you are not subscripting del, you are deleting a list of names.

You can even nest them:

del (foo, [ham, eggs])

It was simpler to re-use an existing grammar rule than to strictly limit the syntax to a comma-separated list of names.

The full grammar definition is:

target_list     ::=  target ("," target)* [","]
target          ::=  identifier
                     | "(" [target_list] ")"
                     | "[" [target_list] "]"
                     | attributeref
                     | subscription
                     | slicing
                     | "*" target

so del *names is technically valid too, but the compiler special-cases that last option to be a SyntaxError anyway:

>>> foo = None
>>> del *foo
  File "<stdin>", line 1
SyntaxError: can't use starred expression here
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
7

It's not indexing.

When deleting things, you can specify more than one thing to delete at a time:

del a, b

You can also surround the deletion targets with brackets or parentheses:

del [a, b]
del (a, b)

And you can do that even if there's only one deletion target:

del [a]

This behavior is mostly mirroring that of assignment, where the optional brackets or parentheses are useful for nested unpacking:

nested_tup = (1, (2, 3))
[a, [b, c]] = nested_tup

While you're technically allowed to do something like del [a, [b, c]], it's equivalent to del a, b, c.

user2357112
  • 260,549
  • 28
  • 431
  • 505