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

The comment by @user2357112 that this seems to be coincidence appears to be correct. The relevant part of the Python source code is in Python/ast.c: switch (e->kind) { # several cases snipped case List_kind: e->v.List.ctx = ctx; s = e->v.List.elts; break; case Tuple_kind: if (asdl_seq_LEN(e->v.Tuple.elts)) { e->v.Tuple.ctx = ctx; s = e->v.Tuple.elts; } else { … Read more

Python: Splat/unpack operator * in python cannot be used in an expression?

Unpacking in list, dict, set, and tuple literals has been added in Python 3.5, as described in PEP 448: Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) on Windows (64 bits). >>> [1, 2, 3, *[4, 5, 6]] [1, 2, 3, 4, 5, 6] Here are some explanations for the rationale behind this change. Note that … Read more

How do I convert a tuple of tuples to a one-dimensional list using list comprehension? [duplicate]

it’s typically referred to as flattening a nested structure. >>> tupleOfTuples = ((1, 2), (3, 4), (5,)) >>> [element for tupl in tupleOfTuples for element in tupl] [1, 2, 3, 4, 5] Just to demonstrate efficiency: >>> import timeit >>> it = lambda: list(chain(*tupleOfTuples)) >>> timeit.timeit(it) 2.1475738355700913 >>> lc = lambda: [element for tupl in … Read more

How does swapping of members in tuples (a,b)=(b,a) work internally?

Python separates the right-hand side expression from the left-hand side assignment. First the right-hand side is evaluated, and the result is stored on the stack, and then the left-hand side names are assigned using opcodes that take values from the stack again. For tuple assignments with 2 or 3 items, Python just uses the stack … Read more