Unpacking patterns

Unpacking patterns#

We’ve generally written Python assignment statements that have only one thing to the left of the = sign. But you can write more complex assignments that unpack the values on the right-hand side.

Here’s an example from mergesort:

At the line marked XXX, we name the result of split—which should be a tuple of lists. We save this tuple as ls and then then index it below. We can use unpacking to simplify things:

Notice how much more concise and clear the code is! Unpacking is a great way to simplify your code. You can do fancier things, too:

The * is a bit like *args—it captures “everything else” as a list. You can only put one star in any unpacking statement.