Can you explain tuple unpacking?

0295

Tuple unpacking in Python is a feature that allows you to assign the elements of a tuple (or any iterable) to multiple variables in a single statement. This makes it easy to extract values without needing to access each element individually.

Example:

# Creating a tuple
person = ("Alice", 30, "Engineer")

# Unpacking the tuple into variables
name, age, occupation = person

print(f"Name: {name}, Age: {age}, Occupation: {occupation}")

Output:

Name: Alice, Age: 30, Occupation: Engineer

Key Points:

  • The number of variables on the left must match the number of elements in the tuple.
  • Tuple unpacking can also be used with lists and other iterable objects.
  • It enhances code readability and reduces the need for indexing.

If you have more questions or need further examples, feel free to ask!

0 Comments

no data
Be the first to share your comment!