Python Unpack Tuples | Meaning, Why and When to Use

Python Unpack Tuples

Tuple unpacking means assigning the elements of a tuple to multiple variables in a single statement. It makes code cleaner and easier to read, especially when returning multiple values from a function or swapping variables.

Tuple unpacking का मतलब है एक tuple के elements को एक ही statement में कई variables में assign करना। यह कोड को साफ और पढ़ने में आसान बनाता है, खासकर जब कोई function कई values return करता है या variables swap करने होते हैं।

Why and When to Use Tuple Unpacking?

  • To assign tuple elements to variables easily and clearly.
  • When functions return multiple values as tuples.
  • For swapping variables without a temporary variable.
  • To extract elements from tuples quickly.
  • Tuple के elements को आसानी से और साफ़ assign करने के लिए।
  • जब functions multiple values tuple के रूप में लौटाते हैं।
  • Variables को बिना temporary variable के swap करने के लिए।
  • Tuple से elements जल्दी निकालने के लिए।
Example 1: Basic Unpacking
t = (10, 20, 30)
a, b, c = t
print(a)
print(b)
print(c)

Assign tuple elements to variables a, b, c.

Tuple के elements को variables a, b, c में assign करें।

Output:

10
20
30
Example 2: Unpacking with Functions
def get_point():
    return (4, 5)
x, y = get_point()
print('x:', x)
print('y:', y)

Unpack multiple return values from a function.

Function से multiple values unpack करें।

Output:

x: 4
y: 5
Example 3: Swapping Variables
a = 5
b = 10
a, b = b, a
print('a =', a)
print('b =', b)

Swap values of variables without a temp variable.

Temporary variable के बिना variables swap करें।

Output:

a = 10
b = 5
Example 4: Unpacking with * Operator
t = (1, 2, 3, 4, 5)
a, *b, c = t
print(a)
print(b)
print(c)

Use * to capture multiple elements as list during unpacking.

* operator से unpacking में multiple elements को list में capture करें।

Output:

1
[2, 3, 4]
5
Example 5: Unpacking Nested Tuples
t = (1, (2, 3), 4)
a, (b, c), d = t
print(a)
print(b)
print(c)
print(d)

Unpack nested tuples into variables.

Nested tuples को variables में unpack करें।

Output:

1
2
3
4