Mastering Python Lists: extracting items from a list and assigning them to multiple variables

You can unpack items from a list in Python by assigning them to multiple variables in a single line. Unpacking is one of the most coder-friendly features in Python, and it works flawlessly when the number of variables aligns with the number of elements in the list.

Basic List Unpacking

If you know exactly how many items the list contains:

Simple one-to-one unpacking: r, g, b = colors assigns each list element to its corresponding variable.


Each list item is assigned to a corresponding variable.

Unpacking With the “Star” Operator (*)

Sometimes you want to capture multiple items at once.
Python’s extended iterable unpacking lets you use a * variable.

Example: Capturing the “rest

Extended unpacking with first, *middle, last = numbers, separating the first item, the last item, and all middle items into a list.


Example: Collecting everything but the first

Here, first, *others = numbers unpacks the first element into first and collects the remaining elements into others.


Or everything but the last

Unpacking with *others, last = numbers, capturing every element except the last into others.


Unpacking in Loops

This works great when iterating through lists of pairs or tuples:

Unpacking inside a loop, where tuple elements are unpacked into x and y while iterating through a list of coordinate pairs.


Unpacking While Ignoring Values

You can use _ as a placeholder for unwanted items:

Using _ as a throwaway variable: first, *_, last = […] captures only the first and last values while ignoring all others.

Quick Summary

When we talk about unpacking, we mean the process of taking elements from a packed data structure, like a list or tuple, and assigning them to separate variables.
Unpacking works in loops, function arguments, and more.

Although my blog doesn’t support comments, feel free to reply via email or X.