Skip to main content
Packing and unpacking are incredibly convenient features in Python that allow you to group multiple values into a single collection, or extract values from a collection directly into individual variables.

Tuple Packing

Packing happens when you assign multiple values to a single variable without any brackets. Python automatically groups these values into a tuple.

Basic Unpacking

Unpacking is the reverse process. It extracts elements from a collection (tuple, list, set, or string) and assigns them to multiple variables in a single line.

Precaution: Variable Count Must Match

When doing basic unpacking, the number of variables on the left must exactly match the number of elements in the collection on the right.

Extended Unpacking with * (Starred Expression)

What if you only want to extract a few elements and group the rest together? Python lets you use the asterisk * operator to capture multiple elements.
You can place the * variable anywhere:
Rule: You can only use one starred expression (*) in a single assignment. Otherwise, Python won’t know how to divide the elements, raising a SyntaxError.

Dictionary Unpacking with **

For dictionaries, you can use the double asterisk ** operator to unpack key-value pairs. This is commonly used to merge multiple dictionaries together.

Unpacking in Loops

Unpacking makes iterating over complex data structures clean and readable.

1. Iterating over list of tuples/lists

2. Using enumerate()

The built-in enumerate() function returns pairs of (index, item), which you can unpack in the loop header:

3. Iterating over dictionary .items()


Key Rules & Common Mistakes

Happens when the number of elements on the right is greater than the number of variables on the left.
Happens when the number of variables on the left is greater than the number of elements on the right.
You cannot have more than one * variable on the left side.

Practice & Exercises

To reinforce what you’ve learned in this section (Tuple packing, basic unpacking, starred expression unpacking, and loop unpacking), practice with these interactive notebooks:

Follow-Along Practice

Practice packing values, basic unpacking, starred unpacking (*), and loop/dictionary merging.💻 VS Code | 🚀 Colab | 📥 Download

Practice Exercises

Test your knowledge with hands-on exercises on coordinate unpacking,Starred Marks partitioning, and configuration dictionary merging.💻 VS Code | 🚀 Colab | 📥 Download

What’s next?

Congratulations! You’ve completed Python Basics. Ready to start building programs?

Building Programs

Learn about functions