Why isn’t assigning to an empty list (e.g. [] = “”) an error?

You are not comparing for equality. You are assigning.

Python allows you to assign to multiple targets:

foo, bar = 1, 2

assigns the two values to foo and bar, respectively. All you need is a sequence or iterable on the right-hand side, and a list or tuple of names on the left.

When you do:

[] = ""

you assigned an empty sequence (empty strings are sequences still) to an empty list of names.

It is essentially the same thing as doing:

[foo, bar, baz] = "abc"

where you end up with foo = "a", bar = "b" and baz = "c", but with fewer characters.

You cannot, however, assign to a string, so "" on the left-hand side of an assignment never works and is always a syntax error.

See the Assignment statements documentation:

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.

and

Assignment of an object to a target list, optionally enclosed in parentheses or square brackets, is recursively defined as follows.

Emphasis mine.

That Python doesn’t throw a syntax error for the empty list is actually a bit of a bug! The officially documented grammar doesn’t allow for an empty target list, and for the empty () you do get an error. See bug 23275; it is considered a harmless bug:

The starting point is recognizing that this has been around for very long time and is harmless.

Also see Why is it valid to assign to an empty list but not to an empty tuple?

Leave a Comment