Skip to content

Week 9 - Tuples

Tuples, Lists, and Dictionaries - Oh My!

Objective:

  1. Create tuples and use tuple operations.
  2. Use tuple assignment and return tuples from functions.
  3. Implement tuple packing and unpacking with functions that handle variable-length arguments.
  4. Utilize zip to iterate through multiple sequences and combine them.
  5. Understand the immutability of tuples and their use as dictionary keys.

Introduction to Tuples

  • Concept: Tuples are similar to lists, but they are immutable.
  • Concept: Use tuples instead of lists when you have data that you don’t want changed, this includes when you need a hash-able key for a dictionary.
  • Code Example:
    1
    2
    3
    fruits = ('apple', 'banana', 'cherry')
    print(fruits[1])  # Access tuple element just like a list
    # fruits[1] = 'orange'  # This will raise a TypeError because tuples are immutable
    

Tuple Creation and Basic Operations

  • Concept: How to create tuples, including single element tuples, and common tuple operations like concatenation, slicing, and duplication.
  • Code Example:
    1
    2
    3
    4
    5
    6
    7
    8
    # Tuple with a single element
    one_element_tuple = ('only',)  # NOTE: the ending comma IS necessary to make it a tuple.
    print(f"Type of one_element_tuple: {type(one_element_tuple)}")
    
    # Concatenation and repetition
    new_tuple = one_element_tuple + ('element',)
    repeated_tuple = new_tuple * 3
    print(repeated_tuple)
    

Tuples as Immutable Objects

  • Concept: Tuples cannot be modified. This immutability allows them to be used as dictionary keys.
  • Code Example:
    1
    2
    location_dict = {('Eureka', 'California'): 'Foggy', ('Las Vegas', 'Nevada'): 'Sunny'}
    print(location_dict[('Eureka', 'California')])  # Using a tuple as a dictionary key
    

Tuple Assignment

  • Concept: Using tuple unpacking to assign multiple variables in one step.
  • Code Example:
    1
    2
    3
    4
    # Swapping values using tuple assignment
    x, y = 5, 10
    x, y = y, x
    print(f"x: {x}, y: {y}")
    

Tuples as Return Values

  • Concept: Returning multiple values from a function using tuples.
  • Code Example:
    1
    2
    3
    4
    5
    def get_min_max(numbers):
        return min(numbers), max(numbers)
    
    result = get_min_max([10, 5, 3, 9, 2])
    print(f"Min: {result[0]}, Max: {result[1]}")
    

Packing and Unpacking Arguments

  • Concept: Functions can pack multiple arguments into a tuple and unpack them for use.
  • Code Example:
    1
    2
    3
    4
    5
    6
    7
    def multiply_all(*numbers):
        result = 1
        for num in numbers:
            result *= num
        return result
    
    print(multiply_all(2, 3, 4))  # Unpacking variable arguments
    

The zip Function

  • Concept: zip allows iterating over multiple sequences simultaneously.
  • Code Example:
    1
    2
    3
    4
    5
    names = ['Alice', 'Bob', 'Charlie']
    scores = [85, 90, 78]
    
    for name, score in zip(names, scores):
        print(f"{name} scored {score}")
    

Comparing and Sorting Tuples

  • Concept: Tuples can be compared and sorted based on lexicographical order.
  • Code Example:
    1
    2
    3
    students = [('Alice', 85), ('Bob', 90), ('Charlie', 78)]
    sorted_students = sorted(students, key=lambda student: student[1], reverse=True)
    print(f"Top student: {sorted_students[0][0]}")
    

Exercises

  1. Tuple Manipulation
    • Create a tuple of your favorite foods. Write a function that takes a tuple of foods and returns a new tuple where all items are reversed.
    • Use slicing with tuples to reverse the items.
  2. Using zip with Lists and Dictionaries
    • Given two lists: keys = ['a', 'b', 'c'] and values = [1, 2, 3], create a dictionary that maps keys to values using zip.
  3. Packing and Unpacking with Functions
    • Write a function that accepts a variable number of arguments, computes their product, and returns both the product and the number of arguments as a tuple.