DEV Community

Vladimir Ignatev
Vladimir Ignatev

Posted on • Updated on

🤔 Python Quiz: Unpacking Sequences in Python

Follow me to learn 🐍 Python in 5-minute a day fun quizzes!

Todays quiz is all about sequences and unpacking them. When you deal with list-type objects or tuples, sequence unpacking come to help! In this quiz guess a proper usage to unpack function arguments and print out user's score!

Sample 1

def process_data(*data):
    name, age, *scores = data
    print(f"Name: {name}, Age: {age}, Scores: {scores}")

process_data("Alice", 30, 75, 85, 90)
Enter fullscreen mode Exit fullscreen mode

Sample 2

def process_data(*data):
    name, *age, scores = data
    print(f"Name: {name}, Age: {age}, Scores: {scores}")

process_data("Bob", 25, 80, 70, 95)
Enter fullscreen mode Exit fullscreen mode

Which code snippet is correct? Post your answer in the comments – is it 0 for the first sample or 1 for the second! As usual, the correct answer will be explained later in comments.

Top comments (1)

Collapse
 
vladignatyev profile image
Vladimir Ignatev

The correct answer is Sample 1.

In Sample 1, the function process_data uses the unpacking feature of Python to neatly extract a name, an age, and a list of scores from the given arguments. The syntax name, age, *scores = data correctly assigns the first two elements of the data to name and age, and the rest of the elements to scores as a list.

Sample 2, however, incorrectly attempts to unpack the data.

This quiz is based on Python's sequence unpacking, which allows for a flexible and readable way to assign values from sequences (like lists or tuples) to variables. This feature is covered in various Python Enhancement Proposals (PEPs) related to tuple unpacking and extended iterable unpacking, such as PEP 3132.