Python Tutorial

Introduction

Edit Template
  • Home
  • /
  • Python Unpack Tuples

Python Tutorial

Introduction

Edit Template
  • Home
  • /
  • Python Unpack Tuples

Python Unpacking Tuples

In Python, unpacking a tuple means pulling apart its items and assigning them to individual variables in one go. This makes code cleaner and easier to read when working with structured data.

Basic Unpacking

Let’s say you have a tuple with three items, and you want each item stored in its own variable:

				
					student_info = ("Hamza", 21, "FAST-NU")

name, age, university = student_info

print("Name:", name)
print("Age:", age)
print("University:", university)

				
			

Output:

				
					Name: Hamza  
Age: 21  
University: FAST-NU

				
			

Each value from the tuple is assigned to its matching variable in the same order.

Unpacking with *

Sometimes, your tuple may have more values than variables. Python lets you capture the “leftovers” using an asterisk * before a variable name.

Example 1: Remaining items stored in the first variable
				
					Land Animals: ['goat', 'cow', 'horse', 'duck']  
Bird: sparrow  
Fish: tuna

				
			

Output:

				
					Land Animals: ['goat', 'cow', 'horse', 'duck']  
Bird: sparrow  
Fish: tuna

				
			
Example 2: Leftovers in the middle
				
					species = ("eagle", "goat", "cow", "duck", "salmon")

bird, *others, fish = species

print("Bird:", bird)
print("Other Animals:", others)
print("Fish:", fish)

				
			

Output:

				
					Bird: eagle  
Other Animals: ['goat', 'cow', 'duck']  
Fish: salmon

				
			
Example 3: Leftovers at the end
				
					species = ("sparrow", "shark", "lion", "tiger", "wolf")

bird, fish, *wild_animals = species

print("Bird:", bird)
print("Fish:", fish)
print("Wild Animals:", wild_animals)

				
			

Output:

				
					Bird: sparrow  
Fish: shark  
Wild Animals: ['lion', 'tiger', 'wolf']

				
			

Final Thoughts

  • Make sure the number of variables matches the structure of the tuple.

  • Use * when you’re unsure how many values you want in a part of the unpacking.

Unpacking gives you clean, readable code and helps break tuples into meaningful pieces — all part of writing smarter Python with Learn With Arshyan.

Scroll to Top