Overview
When creating a Python tuple, items are normally assigned to it (“packing” a tuple).
Extracting the items into variables is called “unpacking” the tuple.
cars = ("Ferrari", "Maserati", "Alfa Romeo")
(car1, car2, car3) = cars
print(car1)
print(car2)
print(car3)
Ferrari
Maserati
Alfa Romeo
Note
The number of variables must match the number of values in the tuple. If not, an asterisk must be used to collect the remaining values as a list.
Using an *
If the number of variables is less than the number of items, an *
can be added to the variable name and the items will be assigned to the variable as a list.
cars = ("Lamborghini", "Ferrari", "Maserati", "Alfa Romeo", "Porsche")
(car1, car2, *car_list) = cars
print(car1)
print(car2)
print(car_list)
Lamborghini
Ferrari
['Maserati', 'Alfa Romeo', 'Porsche']
If the asterisk is added to a variable other than the last, Python will assign items to the variable until the number of items remaining matches the number of variables remaining.
cars = ("Lamborghini", "Ferrari", "Maserati", "Alfa Romeo", "Porsche")
(car1, *car_list, car3) = cars
print(car1)
print(car_list)
print(car3)
Lamborghini
['Ferrari', 'Maserati', 'Alfa Romeo']
Porsche
Python Notes:
- The most recent major version of Python is Python 3; however, Python 2 is still in use and quite popular, although not being updated with anything other than security updates
- Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses
- Python relies on indentation, using whitespace to define scope, such as the scope of loops, functions, and classes; other programming languages often use curly-brackets for this purpose
- Python string methods return new values, and DO NOT change the original string
We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.