Unpacking Python Tuples
When you create a Tuple using the (...)
syntax it's called packing a Tuple.
Python
Copy Code
letters = ( 'A', 'B', 'C')
The reverse is to unpack a Tuple
Python
Copy Code
letters = ( 'A', 'B', 'C') (letterA, letterB, letterC) = letters print(letterA) # prints 'A' print(letterB) # prints 'B' print(letterC) # prints 'C'
If we supply fewer variables in our unpack list than there are elements in the Tuple an error will be thrown.
Python
Copy Code
letters = ( 'A', 'B', 'C', 'D') (letterA, letterB, letterC) = letters
Output
ValueError: too many values to unpack (expected 3)
'Expected 3' means Python expected 3 values since there there 3 variables provided to take the values.
For this situation you can use the *
operator on the last variable to instruct Python
to pack all remaining items into that last variable as a List.
Python
Copy Code
letters = ( 'A', 'B', 'C', 'D') (letterA, letterB, *theRest) = letters print(letterA) # prints 'A' print(letterB) # prints 'B' print(theRest) # prints the List ['C', 'D']