Loading...

Python Unpacking

One line can give each value its own name. drink, food = ["tea", "rice"] puts tea in drink and rice in food. The first name takes the first value. The second name takes the second. drink and food do not need a place number.

tea in drink, rice in food

python
drink, food = ["tea", "rice"]

print(drink)
print(food)

The screen shows tea, then rice. drink already holds tea. food already holds rice. The left side has no name for the list, so the list is not kept under another name.

You can keep the list and still pull the values out. This program starts on its own. plate is tea, then rice. drink, food = plate reads that list into the two names. plate stays the list.

food is rice, and the list still starts with tea

python
plate = ["tea", "rice"]
drink, food = plate

print(food)
print(plate[0])

The screen shows rice, then tea. food is rice, the second value. plate[0] is still tea, so the list was not emptied and the order inside it did not change. drink is tea too, and this program does not print drink.

One name on the left does not open the list. meal = ["tea", "rice"] stores the whole list under meal. meal is not the word tea. When you want one food, you still pick a place.

one name, length 2, place 1 is rice

python
meal = ["tea", "rice"]

print(len(meal))
print(meal[1])

The screen shows 2, then rice. The 2 is how long the list is under the single name meal. Place 1 is rice. Place 0 is tea, and this program does not print it.

The number of names has to match the number of values. drink, food = ["tea"] stops: two names, one value. drink, food, extra = ["tea", "rice"] stops: three names, two values. Python does not put None in the spare name. The program stops.

The next page builds a new list in one line. This page only gives names to values that are already written.

What the three programs write

  1. What does the first program write?
  2. What does the second program write?
  3. What does the third program write?
  4. What happens if you write drink, food = ["tea"]?

Names in the same order as the values

The first screen is tea, then rice. drink and food hold those texts, with no place number. The second screen is rice, then tea, and plate still starts with tea. One name keeps the whole list, so the third screen is 2, then rice. If the counts do not match, the program stops. The next page builds a list in one line.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
5
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top