Skip to main content
Practice

Using Functions and Tuples Together

Immune to modification once defined, tuples are particularly efficient when used with functions.

An important feature when using tuples with functions is packing and unpacking.

Packing refers to the process of combining multiple data into a single tuple.

The example below packs name, age, and occupation into a tuple called person.

Tuple Packing Example
# Tuple packing: combining multiple values into a single tuple
person = ("Alice", 25, "Engineer")
# Or simply: person = "Alice", 25, "Engineer"

Unpacking means separating the data packed within a tuple into individual elements.

In the example below, the values packed in the person tuple are unpacked into variables name, age, and job.

Tuple Unpacking Example
# Tuple unpacking: separating packed values into individual elements
name, age, job = person
print(name) # Alice
print(age) # 25
print(job) # Engineer

Unpacking to Separate Values

You can easily extract specific parts of packed values using unpacking.

Tuple Unpacking Example
# Unpacking the first value and the rest
first, *rest = (1, 2, 3, 4, 5)
# 1
print(first)
# [2, 3, 4, 5]
print(rest)

# Unpacking all but the first and last values
first, *middle, last = (10, 20, 30, 40, 50)
# 10
print(first)
# [20, 30, 40]
print(middle)
# 50
print(last)

Returning and Unpacking Tuples from Functions

Tuples can be used when returning multiple values from a function using the return keyword.

The example below shows a function calculate that returns the results of a + b and a * b as a tuple, which is then unpacked for use.

Returning Tuples from a Function
# Function returning multiple values
def calculate(a, b):
return a + b, a * b

# Unpacking the returned tuple
sum_result, product_result = calculate(3, 5)

# Sum: 8
print(f"Sum: {sum_result}")
# Product: 15
print(f"Product: {product_result}")

In the code above, the variables sum_result and product_result store the results of a + b and a * b, respectively.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.