Unpacking in Python: Beyond Parallel Assignment

python_tutorials

Introduction

Unpacking in Python refers to an operation that consists of assigning an iterable of values to a tuple (or list) of variables in a single assignment statement. As a complement, the term packing can be used when we collect several values in a single variable using the iterable unpacking operator, *.

Historically, Python developers have generically referred to this kind of operation as tuple unpacking. However, since this Python feature has turned out to be quite useful and popular, it’s been generalized to all kinds of iterables. Nowadays, a more modern and accurate term would be iterable unpacking.

In this tutorial, we’ll learn what iterable unpacking is and how we can take advantage of this Python feature to make our code more readable, maintainable, and pythonic.

Additionally, we’ll also cover some practical examples of how to use the iterable unpacking feature in the context of assignments operations, for loops, function definitions, and function calls.

Packing and Unpacking in Python

Python allows a tuple (or list) of variables to appear on the left side of an assignment operation. Each variable in the tuple can receive one value (or more, if we use the * operator)

To finish reading, please visit source site