[Python-ideas] Generator unpacking
Steven D'Aprano
steve at pearwood.info
Mon Feb 15 09:42:52 EST 2016
On Mon, Feb 15, 2016 at 02:55:26PM +0100, Sven R. Kunze wrote:
> On 15.02.2016 07:31, Andrew Barnert via Python-ideas wrote:
> >> [] = []
> >
> >Yes, but that's completely different. The [] on the left isn't an
> >expression, or even a target, but a target list with 0 targets in it.
[..]
> Interestingly, doing the following results in an syntax error.
>
> >>> [1,2]=[3,4]
>
> File "<input>", line 1
> SyntaxError: can't assign to literal
>
>
> So, if it's illegal to assign to the literal [1,2], I don't see why it
> should be legal for []. But as you said, that's a highly theoretical
> problem.
I believe you are misinterpreting the error. The error isn't that you
are trying to assign to the literal [1,2]. The error is that you are
trying to assign to the literal 1. It's a subtle difference, but
important to understand that difference in order to understand why [] is
a legal assignment target.
py> [a, b, c, 1] = "abcd"
File "<stdin>", line 1
SyntaxError: can't assign to literal
Obviously [a, b, c, 1] is not a literal, but 1 is. If there is any
doubt:
py> [a, b, c, None] = "abcd"
File "<stdin>", line 1
SyntaxError: cannot assign to None
Since [1,2] is a *list of assignment targets*, not a single target, the
assignment you attempted
[1, 2] = [3, 4]
is roughly equivalent to:
1 = 3
2 = 4
which obviously gives a syntax error.
[] is a valid assignment target so long as the right hand side is an
empty iterable. If it is not empty, you get a TypeError:
py> [] = "abc"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
There are three values on the right hand side, and zero targets.
This might even be useful. You can confirm that an iterable is empty
(why you might want to do this, I can't imagine, but suppose you did) by
assigning it to zero targets:
[] = iterable
succeeds only if iterable has zero items, otherwise it raises
TypeError.
--
Steve
More information about the Python-ideas
mailing list