How to Unpack a List in Python

Summary: in this tutorial, you’ll learn how to unpack a list in Python to make your code more concise.

Introduction to the list unpacking

The following example defines a list of strings:

colors = ['red', 'blue', 'green']Code language: Python (python)

To assign the first, second, and third elements of the list to variables, you may assign individual elements to variables like this:

red = colors[0] blue = colors[1] green = colors[2] Code language: Python (python)

However, Python provides a better way to do this. It’s called sequence unpacking.

Basically, you can assign elements of a list (and also a tuple) to multiple variables. For example:

red, blue, green = colorsCode language: Python (python)

This statement assigns the first, second, and third elements of the colors list to the redblue, and green variables.

In this example, the number of variables on the left side is the same as the number of elements in the list on the right side.

If you use a fewer number of variables on the left side, you’ll get an error. For example:

colors = ['red', 'blue', 'green'] red, blue = colors Code language: Python (python)

Error:

ValueError: too many values to unpack (expected 2)Code language: Python (python)

In this case, Python could not unpack three elements to two variables.

Unpacking and packing

If you want to unpack the first few elements of a list and don’t care about the other elements, you can:

  • First, unpack the needed elements to variables.
  • Second, pack the leftover elements into a new list and assign it to another variable.

By putting the asterisk (*) in front of a variable name, you’ll pack the leftover elements into a list and assign them to a variable. For example:

colors = ['red', 'blue', 'green'] red, blue, *other = colors print(red) print(blue) print(other) Code language: Python (python)

Output:

red blue ['green']Code language: Python (python)

This example assigns the first and second elements of the colors list to the red and green variables. And it assigns the last element of the list to the other variable.

Here’s another example:

colors = ['cyan', 'magenta', 'yellow', 'black'] cyan, magenta, *other = colors print(cyan) print(magenta) print(other) Code language: Python (python)

Output:

cyan magenta ['yellow', 'black']Code language: Python (python)

This example assigns the first and second elements to variables. It packs the last two elements in a new list and assigns the new list to the other variable.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *