Monday 2 September 2024

5 Essential Tuple Unpacking Techniques

 

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

Popular Posts

Categories

AI (29) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (122) C (77) C# (12) C++ (82) Course (67) Coursera (195) Cybersecurity (24) data management (11) Data Science (100) Data Strucures (7) Deep Learning (11) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (46) Meta (18) MICHIGAN (5) microsoft (4) Pandas (3) PHP (20) Projects (29) Python (837) Python Coding Challenge (279) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (41) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses