PYTHON

Efficiently Swap Variables and Unpack Tuples

Learn Python's elegant way to swap variable values without temporary variables and efficiently unpack tuple elements into distinct variables for cleaner, more readable code.

# 1. Swapping two variables without a temporary variable
a = 10
b = 20

print(f"Before swap: a={a}, b={b}") # Output: Before swap: a=10, b=20
a, b = b, a
print(f"After swap: a={a}, b={b}")  # Output: After swap: a=20, b=10

# 2. Assigning multiple variables from a tuple (unpacking)
coordinates = (100, 200, 300)
x, y, z = coordinates
print(f"Coordinates: x={x}, y={y}, z={z}") # Output: Coordinates: x=100, y=200, z=300

# 3. Selective unpacking using '*' (Python 3)
data = [1, 2, 3, 4, 5, 6]
first, *middle, last = data
print(f"First: {first}, Middle: {middle}, Last: {last}") # Output: First: 1, Middle: [2, 3, 4, 5], Last: 6

# 4. Unpacking with iteration
points = [(1, 2), (3, 4), (5, 6)]
for px, py in points:
    print(f"Point: ({px}, {py})")
How it works: This snippet showcases Python's powerful tuple unpacking feature. The first example demonstrates how to swap two variables concisely by assigning them simultaneously, implicitly creating a temporary tuple on the right-hand side. The second example shows basic tuple unpacking, where elements of a tuple are assigned to individual variables. The third example uses the `*` operator for 'starred assignment', allowing you to capture multiple elements into a list, useful for lists or tuples of varying lengths. Finally, unpacking is frequently used in `for` loops to iterate over sequences of tuples, directly assigning components to separate variables for convenience.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs