What is Unpacking in Python?
Unpacking in Python is a technique that allows you to assign multiple elements from an iterable (like a list, tuple, or dictionary) to variables at once.
* is used to unpack sequences like lists or tuples, and ** is used to unpack dictionaries. This feature provides a more readable and efficient way to handle multiple items simultaneously.
Why Use Unpacking?
Unpacking is valuable when working with collections of data, as it allows you to retrieve multiple values at once. For example, if you have a list of barangay officials, you might want to designate the first as the leader, others as members, and the last as the finance head. With unpacking, this is easy to implement.
Syntax
- Use * to unpack lists or tuples.
- Use ** to unpack dictionaries.
*args, **kwargs first, *middle, last = sequence {**dict1, **dict2}
Example
Let’s say we want to unpack a list of barangay officials and barangay budget allocations, we can easily do it by unpacking.
# A list of Barangay officials barangay_officials = ("Captain", "Councilor", "Secretary", "Treasurer") # Unpack the first and last official, and group the rest leader, *members, finance = barangay_officials print("Barangay Leader:", leader) # Barangay Leader: Captain print("Council Members:", members) # Council Members: ['Councilor', 'Secretary'] print("Finance Head:", finance) # Finance Head: Treasurer # Barangay resources with budget allocations barangay_budget = {"Health": 20000, "Education": 15000, "Infrastructure": 30000} additional_funds = {"Emergency": 5000, "Culture": 8000} # Combine barangay budgets total_budget = {**barangay_budget, **additional_funds} print("Total Barangay Budget Allocation:", total_budget) # {'Health': 20000, 'Education': 15000, 'Infrastructure': 30000, 'Emergency': 5000, 'Culture': 8000}