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.
* variable anywhere:
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
ValueError: too many values to unpack
ValueError: too many values to unpack
Happens when the number of elements on the right is greater than the number of variables on the left.
ValueError: not enough values to unpack
ValueError: not enough values to unpack
Happens when the number of variables on the left is greater than the number of elements on the right.
SyntaxError: two starred expressions in assignment
SyntaxError: two starred expressions in assignment
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 | 📥 DownloadPractice 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