Packing and Unpacking Lists and Tuples
Swipe to show menu
Packing and unpacking with the * operator is a powerful feature in Python that allows you to write concise and flexible code, especially when working with lists and tuples. Packing refers to collecting multiple values into a single variable, while unpacking breaks a collection apart into individual variables or elements. This approach not only makes your code cleaner but also enables you to handle dynamic numbers of values in assignments and function calls. Using the * operator, you can easily expand or combine sequences, making your code both readable and efficient.
This code demonstrates how to unpack a tuple into variables and pack multiple values into a tuple using the * operator.
Unpacking assigns each element of a tuple to a separate variable, while packing collects remaining elements into a list.
1234567891011# Unpacking a tuple into variables coordinates = (10, 20) coord_x, coord_y = coordinates print("x:", coord_x) print("y:", coord_y) # Packing multiple values into a tuple first_val, second_val, *rest = (1, 2, 3, 4, 5) print("first_val:", first_val) print("second_val:", second_val) print("rest:", rest)
Code unpacks a list into individual arguments when calling a function. This allows you to pass a sequence as separate arguments, making function calls more flexible.
1234567# Using * to unpack a list into a function call def add_three_numbers(a, b, c): return a + b + c numbers = [2, 4, 6] result = add_three_numbers(*numbers) print(result)
1. What does the * operator do when used in a function call with a list?
2. Which of the following is a correct way to unpack a tuple of three elements into three variables in Python?
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat