Is there a more elegant way for unpacking keys and values of a dictionary into two lists, without losing consistence?
keys, values = zip(*d.items())
keys, values = zip(*d.items())
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
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
in python 2.X, you can do: c = (1, 2, 3) a, b = c[0], c[1:] as long as c has at least one member it will work because if c only has 1 thing in it c[1:] is []. You should probably make sure there is at least one thing in c though, or … Read more
there is also another way of doing it by looping through the items in d. this doesn’t have the same assuption that they will get stored in c.__dict__ which isn’t always true. d = {‘bar’: 456} for key,value in d.items(): setattr(c,key,value) or you could write a update method as part of MyClass so that c.update(d) … Read more
In Python the _ is often used as an ignored placeholder. (path, _) = self._treeView.get_cursor() You could also avoid unpacking as a tuple is indexable. def get_selected_index(self): return self._treeView.get_cursor()[0][0]
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
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
Taking a quote from the Py-Dev mailing list thread in which this feature was accepted: So that leaves comprehensions. IIRC, during the development of the patch we realized that f(*x for x in xs) is sufficiently ambiguous that we decided to disallow it — note that f(x for x in xs) is already somewhat of … Read more