PythonTuplesPractice Problems

Tuple Practice Lab

Apply your knowledge of tuples with these hands-on challenges. Each problem includes a detailed explanation of the solution.

Challenge 1: Variable Swapping

This is the classic Pythonic use of tuple unpacking.

Pyground

Swap the values of two variables, `a` and `b`, without using a temporary variable.

Expected Output:

Before -> a: first, b: second
After  -> a: second, b: first

Output:

Challenge 2: Function Returning Multiple Values

It’s a common pattern for functions to return multiple results as a tuple. Unpacking makes it easy to capture these results.

Pyground

Write a function that analyzes a list of numbers and returns a tuple containing the minimum, maximum, and average. Unpack the result into separate variables.

Expected Output:

Data: [10, 20, 5, 15, 25]
Min: 5, Max: 25, Average: 15.00

Output:

Challenge 3: Processing Records with Unpacking in a Loop

Unpacking is extremely powerful inside for loops when iterating over a list of tuples.

Pyground

Given a list of (city, temperature) tuples, print a formatted report for cities where the temperature is above 25 degrees.

Expected Output:

Hot Cities Report:
- Mumbai: 29°C
- Bengaluru: 27°C
- Chennai: 31°C

Output:

Challenge 4: Using a Named Tuple for Readability

Improve data access by using collections.namedtuple to create readable, self-documenting records.

Pyground

Define a 'Book' named tuple with fields 'title', 'author', and 'year'. Create a list of Book objects and print their details.

Expected Output:

'1984' by George Orwell, published in 1949.
'Brave New World' by Aldous Huxley, published in 1932.

Output:

Challenge 5: Sorting with a Composite Key

Use tuples as keys for sorting a list based on multiple criteria.

Pyground

Sort a list of files first by file type ('mp4', 'jpg', 'txt') and then by size (ascending).

Expected Output:

photo.jpg       |  1500 bytes
image.jpg       |  2100 bytes
video.mp4       |  5400 bytes
document.txt    |   800 bytes

Output: