Skip to content

Computer Science · Ch 10 — Tuples and Dictionaries

Tuple Handling

10.6

Tuple Handling

This section puts tuples to work in three complete programs, each showing a practical tuple idiom: swapping values with tuple assignment, returning multiple values from a function, and growing a tuple element-by-element with concatenation.

Escape characters used below: \t inserts a horizontal tab space, and \n inserts a new line.

Program 1 — swap two numbers without a temporary variable

Tuple assignment lets both variables receive their new values simultaneously, so no third variable is needed:

# Program to swap two numbers
num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))

print("\nNumbers before swapping:")
print("First Number:", num1)
print("Second Number:", num2)

(num1, num2) = (num2, num1)     # the swap — one tuple assignment

print("\nNumbers after swapping:")
print("First Number:", num1)
print("Second Number:", num2)

Output:

Enter the first number: 5
Enter the second number: 10

Numbers before swapping:
First Number: 5
Second Number: 10

Numbers after swapping:
First Number: 10
Second Number: 5

The right side (num2, num1) is built first, then unpacked into (num1, num2) — which is exactly why the values cross over cleanly.

Program 2 — a function returning two values (area and circumference of a circle)

A Python function can hand back more than one value by returning them packed in a tuple; the caller unpacks them with tuple assignment:

# Function to compute area and circumference of a circle
def circle(r):
    area = 3.14 * r * r
    circumference = 2 * 3.14 * r
    # return a tuple carrying both results
    return (area, circumference)
# end of function

radius = int(input('Enter radius of circle: '))
area, circumference = circle(radius)     # unpack the returned tuple
print('Area of circle is:', area)
print('Circumference of circle is:', circumference)

Output:

Enter radius of circle: 5
Area of circle is: 78.5
Circumference of circle is: 31.[PII:card]

Program 3 — read n numbers into a tuple, then find the maximum and minimum

Since a tuple cannot be modified in place, we grow it by concatenating a one-element tuple (num,) in each loop pass — every concatenation creates a new tuple bound back to the same name:

# Input n numbers from the user, store them in a tuple,
# then print the maximum and minimum number from the tuple
numbers = tuple()          # create an empty tuple 'numbers'
n = int(input("How many numbers you want to enter?: "))
for i in range(0, n):
    num = int(input())
    # append the entered number to the tuple 'numbers' …