Tuple unpacking allows you to assign multiple variables at the same time. Normally, you would need to manually create each variable to extract the values of a tuple. However, Python has made it much easier to do this.
Normally, you would do this:
# Extracting values from "countries" countries = ("china", "mexico", "brazil", "USA") a = countries b = countries c = countries d = countries print(a, b, c, d) # prints "china mexico brazil USA"
Python has a special way to extract tuple values:
a, b, c, d = countries print(a, b, c, d) # prints "china mexico brazil USA"
There are many other special features of tuple unpacking that may be useful to you:
# Using the * says that you want all values # in the middle of the tuple to be put together # in a list. a, *b, c = countries print(a, b, c) # prints "china ["mexico", "brazil"] USA"
Contrary to the name, tuple unpacking also works on lists, too. Look back at the previous examples. If the tuple was actually a list, this feature would still work.
View code on GitHub.
A messy teacher named Bob would like to add 10 points to each student’s recent test score. There are four students, and going from highest score to lowest score, they are Mike, Dan, Stan, and Ban. Add 10 to each score and assign those values to the correct student. Solve this problem by adding no more than 2 lines of code.
Hint: Use tuple unpacking and list comprehension.
A hacker named Dan wishes to hack into a competition where they judge participants in three categories on a scale of 10. Dan wants his friend Bob to win. Bob will only win if he has all 10s while the other competitors, Jo and Stan, don’t.
Judges will store the scoring within a tuple
([...], [...], [...]). The scores before Dan hacked are given. Bob will be located as the first person the judges scored and will have the lowest points out of any participant. Create a program to help Dan help Bob win. Also, print Bob’s score at the end. Use tuple unpacking to solve this problem.
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact firstname.lastname@example.org for inquiries.