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

Getting only element from a single-element list in Python?

Raises exception if not exactly one item: Sequence unpacking: singleitem, = mylist # Identical in behavior (byte code produced is the same), # but arguably more readable since a lone trailing comma could be missed: [singleitem] = mylist Rampant insanity, unpack the input to the identity lambda function: # The only even semi-reasonable way to … Read more

Unpacking, extended unpacking and nested extended unpacking

My apologies for the length of this post, but I decided to opt for completeness. Once you know a few basic rules, it’s not hard to generalize them. I’ll do my best to explain with a few examples. Since you’re talking about evaluating these “by hand,” I’ll suggest some simple substitution rules. Basically, you might … 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

“unpacking” a tuple to call a matching function pointer

You need to build a parameter pack of numbers and unpack them template<int …> struct seq { }; template<int N, int …S> struct gens : gens<N-1, N-1, S…> { }; template<int …S> struct gens<0, S…> { typedef seq<S…> type; }; // … void delayed_dispatch() { callFunc(typename gens<sizeof…(Args)>::type()); } template<int …S> void callFunc(seq<S…>) { func(std::get<S>(params) …); … Read more