Editor settings

General settings

Save settings

Learn to program with Python

Data unpacking in Python #

Data unpacking in Python refers to the process of extracting values from a data structure, such as a tuple or a list, and assigning them to individual variables. It allows you to conveniently access and work with the elements of a collection without explicitly indexing them.

Here's a simple example to demonstrate data unpacking:

# Tuple with three elements
person = ('John', 25, 'London')

# Unpacking the tuple into separate variables
name, age, city = person

# Accessing the unpacked values
print(f"Name: {name}")
print(f"Age: {age}")
print(f"City: {city}")

Output:

Name: John
Age: 25
City: London

In this example, the tuple person contains three elements: the name, age, and city of a person. By assigning these elements to the variables name, age, and city in a single line, we unpack the values from the tuple. Each variable is assigned the corresponding value from the tuple, allowing us to access and work with them individually.


Exercise #

Unpack the values from the variable employee into variables name, age, and department respectively.

Tests #

  • Variable employee should be "Jane Smith"
  • Variable age should be 28
  • Variable department should be "Marketing"
  • Use data unpacking to assign all 3 variables in a single line
Output will be displayed here