
Edit: Looks like this has been fixed for python 3.5.2 and 3.6. See PEP 448 (Additional Unpacking Generalizations) and PEP 3132 (Extended Iterable Unpacking).

Often star-unpacking is called 'iterable unpacking' for this reason. The BINARY_SUBSCR opcode is only optimized for python lists anything that isn't a native python list requires a PyObject_GetItem call. should really say, argument after must be an iterable.

Python unpacking sequence code#
The above code reaches into the native structure of the tuple and retrieves the values directly no need to use heavy calls such as PyObject_GetItem which have to take into account that the object could be a custom python class. } // followed by an "else if" statement for a list with similar code And that’s it The asterisk,, or unpacking operator, unpacks numlist, and passes the values, or elements, of numlist as separate arguments to the numsum function. The UNPACK_SEQUENCE opcode source code special-cases a python tuple or list unpack where the the sequence length matches the argument length exactly: if (PyTuple_CheckExact(v) & For example, if we want to unpack numlist and pass in the 5 elements as separate arguments for the numsum function, we could do so as follows: numsum(numlist) 15. In this post, I will walk through the process of unpacking different types of sequences in python. The unpack operation can take place, inline, in the python evaluation loop, while the subscription call requires looking up of the function on the tuple object to retrieve the value, using PyObject_GetItem. Packing and Unpacking a Tuple: In Python, there is a very powerful tuple assignment feature that assigns the right-hand side of values into the left-hand side. The tuple unpacking operation is a simple bytecode ( UNPACK_SEQUENCE), while the indexing operation has to call a method on the tuple ( BINARY_SUBSCR).

We can use the iterable unpacking operator when defining sequences to unpack the elements of a subsequence (or iterable) into the final sequence. If you take a look at the python bytecode, it becomes quite obvious very quickly why unpacking is faster: > import dis Python Packing and Unpacking Arguments in Python with tutorial, tkinter, button, overview, canvas, frame, environment set-up, first python program, etc.
