1. Basic Tuple Unpacking
person = ("John", 28, "Engineer")
name, age, profession = person
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Profession: {profession}")
Name: John
Age: 28
Profession: Engineer
Explanation: This program unpacks a tuple containing personal details into individual variables.
2. Swapping Variables Using Tuple Unpacking
a = 5
b = 10
a, b = b, a
print(f"a: {a}")
print(f"b: {b}")
a: 10
b: 5
Explanation: This program swaps the values of two variables using tuple unpacking in a single line.
3. Unpacking Elements from a List of Tuples
students = [("Alice", 85), ("Bob", 90), ("Charlie", 88)]
for name, score in students:
print(f"Student: {name}, Score: {score}")
Student: Alice, Score: 85
Student: Bob, Score: 90
Student: Charlie, Score: 88
Explanation: This program iterates over a list of tuples and unpacks each tuple into individual variables within a loop.
4. Unpacking with * (Star Operator)
numbers = (1, 2, 3, 4, 5, 6)
first, second, *rest = numbers
print(f"First: {first}")
print(f"Second: {second}")
print(f"Rest: {rest}")
First: 1
Second: 2
Rest: [3, 4, 5, 6]
Explanation: This program uses the * (star) operator to unpack the first two elements of a tuple and collect the rest into a list.
5. Returning Multiple Values from a Function Using Tuple Unpacking
def get_student_info():
name = "Eve"
age = 22
major = "Computer Science"
return name, age, major
student_name, student_age, student_major = get_student_info()
print(f"Name: {student_name}")
print(f"Age: {student_age}")
print(f"Major: {student_major}")
Name: Eve
Age: 22
Major: Computer Science
Explanation: This program demonstrates how a function can return multiple values as a tuple, which can then be unpacked into individual variables when called.
0 Comments:
Post a Comment