Unpacking with * and ** to Simplify Multiple Variable Assignment

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.

Tutorials dojo strip

Syntax

  • Use * to unpack lists or tuples.
  • Use ** to unpack dictionaries.

Example

Let’s say we want to unpack a list of barangay officials and barangay budget allocations, we can easily do it by unpacking.

Tutorials dojo strip