Course Q2 Prep from DeepSeek: Lists and Tuples

Prompt: imagine you are a professor and you want me to fail on this quiz, on this midterm, so you give me the most tricky questions. Now I will write everything that we have studied on one presentation. It is a presentation about lists and tuples and there is going to be subtopics. So I'm just gonna announce you where the subtopic, new subtopic starts. So for each subtopic, give me six practice questions to write code, each with adding slightly more difficulty, six questions to interpret code, also each with adding difficulty for all subtopics of this presentation. Okay, the first subtopic is ……….. And as again, do the tasks for each sub-topic. give me most useful and tricky questions for each subtopic to write and interpret - for interpret questions give me questions that are extremely difficult for each subtopic. WORK WELL FOR THIS STUDY FILE BECAUSE IT'S EXTREMELY IMPORTANT, I NEED TO LEARN HOW TO INTERPRET EVERYTHING CORRECTLY WHEN PROFESSOR WANTS ME TO FAIL, KNOW HOW TO WRITE CODE WITH EACH SUBTOPIC, PLUS AT THE END GIVE ME CORRECT ANSWERS FOR EACH QUESTION


Subtopic 1: Creating Lists, Slicing, len(), max(), sum(), shuffle()

Code Writing Questions (Increasing Difficulty)
  1. Basic: Create a list named colors containing the strings "red", "green", and "blue". Then, print the length of the list.

  2. Intermediate: Given the string data = "10,20,30,40,50", create a list of integers from it. Then, calculate and print the sum of all numbers except the first and the last.

  3. Intermediate: Create a list of 15 numbers, starting from 5 and ending at 33, stepping by 2. Then, using slicing, create a new list containing only the first 3 and the last 3 elements of the original list.

  4. Advanced: Write a function list_manipulator(input_list) that takes a list of numbers. The function should: (a) Create a shuffled copy of the list without modifying the original. (b) Find the maximum value in the original list. (c) Return the index of that maximum value in the shuffled list. (You'll need random.shuffle and list.index()).

  5. Advanced: You have a list of strings: words = ["apple", "banana", "cherry", "date"]. Create a new list where each element is a list containing the length of the word and the word itself, but only for words whose length is greater than 5. E.g., [[6, 'banana']].

  6. Expert: Write a single line of code using a list comprehension and slicing to generate the following list: [1, 3, 5, 7, 9, 19, 17, 15, 13, 11]. Hint: You'll need to generate two sequences and combine them.

Code Interpretation Questions (Increasing Difficulty)

What is the exact output of the following code snippets?

  1. Basic:

    python

    my_list = [1, 2, 3, 4, 5]
    print(my_list[-1] + my_list[0])
  2. Intermediate:

    python

    my_list = [10, 20, 30, 40, 50, 60]
    result = my_list[1:4] + my_list[5:]
    print(result)
  3. Intermediate:

    python

    my_list = [1, 2, 3, 4, 5]
    sliced = my_list[1:4]
    sliced[1] = 99
    print(my_list)
    print(sliced)
  4. Advanced:

    python

    import random
    data = [1, 2, 3, 4, 5]
    random.seed(42)  # Assume this makes the shuffle predictable for this example: [1, 5, 3, 4, 2]
    shuffled_data = data[:]
    random.shuffle(shuffled_data)
    result = [shuffled_data[i] for i in range(len(data)) if data[i] == shuffled_data[i]]
    print(result)
  5. Advanced:

    python

    my_list = [1, 2, 3, 4, 5, 6]
    slice1 = my_list[::2]
    slice2 = my_list[-2::-2]
    print(f"{slice1} - {slice2}")
  6. Expert:

    python

    original = [1, 2, 3, 4, 5]
    a = original[1:4]
    b = original
    c = original[:]
    
    a[0] = 99
    b[1] = 88
    c[2] = 77
    
    print(f"original: {original}")
    print(f"a: {a}")
    print(f"b: {b}")
    print(f"c: {c}")

Subtopic 2: Comparing Lists, append(), extend(), insert()

Code Writing Questions (Increasing Difficulty)
  1. Basic: Create a list list_a = [1, 2, 3]. Use a method to add the single number 4 to the end of list_a. Print the result.

  2. Intermediate: Create two lists: list1 = [1, 2, 3] and list2 = [1, 2, 3]. Write an if statement that prints "Lists are equal" if they have the same elements in the same order, and "Lists are different" otherwise.

  3. Intermediate: Create a list tasks = ["write report"]. Use the most appropriate method to add the elements "email client" and "review code" to tasks so that the final list is ["write report", "email client", "review code"].

  4. Advanced: You have a list names = ["Alice", "Charlie", "David"]. Insert the name "Bob" into the list at the correct position to maintain alphabetical order. Do this without using sort() or creating a new list.

  5. Advanced: Write a function custom_extend(target_list, source_list) that manually replicates the behavior of target_list.extend(source_list). It should take two lists and modify the first list by appending all elements from the second list. It should not return a new list.

  6. Expert: You have a list of numbers: nums = [10, 20, 30, 40, 50]. Write code to insert the average of any two consecutive numbers between them. The final list should look like: [10, 15.0, 20, 25.0, 30, 35.0, 40, 45.0, 50].

Code Interpretation Questions (Increasing Difficulty)

What is the exact output of the following code snippets?

  1. Basic:

    python

    list_a = [1, 2]
    list_b = [1, 2]
    list_c = list_a
    
    print(list_a == list_b)
    print(list_a is list_b)
    print(list_a is list_c)
  2. Intermediate:

    python

    list1 = [1, 2, 3]
    list2 = [4, 5, 6]
    list1.append(list2)
    print(list1)
  3. Intermediate:

    python

    list1 = [1, 2, 3]
    list2 = [4, 5, 6]
    list1.extend(list2)
    print(list1)
  4. Advanced:

    python

    original = [1, 2, 3, 4]
    result = original.insert(2, original.pop())
    print(original)
    print(result)
  5. Advanced:

    python

    list_a = [10, 20]
    list_b = [30, 40]
    list_a.append(list_b.pop(0))
    list_b.extend(list_a)
    print(f"list_a: {list_a}")
    print(f"list_b: {list_b}")
  6. Expert:

    python

    a = [1, 2, 3]
    b = [4, 5, 6]
    c = [7, 8, 9]
    
    temp = a
    a = a + [b[1], c[1]]
    temp.extend([b[1], c[1]])
    
    print(f"a: {a}")
    print(f"temp: {temp}")
    print(f"b: {b}")
    print(f"c: {c}")

Subtopic 3: Functions on Lists (split(), List Comprehensions)

Code Writing Questions (Increasing Difficulty)
  1. Basic: Given the string sentence = "the quick brown fox", use the split() function to create a list of the words. Then, use a list comprehension to create a new list containing the lengths of each word.

  2. Intermediate: Given the string data = "name:John,age:30,city:NYC", split it first by commas, and then for each resulting string, split by colon to create a list of [key, value] pairs. The final result should be a list of lists. E.g., [['name', 'John'], ['age', '30'], ['city', 'NYC']].

  3. Intermediate: Use a single list comprehension to generate a list of the squares of even numbers from 1 to 20.

  4. Advanced: Write a function process_scores(scores) that takes a string like "45,67,89,12,90,33". The function should split the string, convert to integers, and use a list comprehension with an if-else to create a new list where scores below 40 are replaced with "FAIL" and others remain as integers. E.g., for the string above, the output should be [45, 67, 89, 'FAIL', 90, 'FAIL'].

  5. Advanced: You have a string text = "Hello world, how are you?". Use split() and list comprehension to create a list of words, but exclude any word that contains the letter 'o'. Print the result.

  6. Expert: You are given a string "apple banana apple cherry date banana apple". Write code (potentially using split(), list comprehension, and other list methods) to create a new list containing only the unique words, but sorted by their frequency of occurrence in the original string (most frequent first). If two words have the same frequency, sort them alphabetically.

Code Interpretation Questions (Increasing Difficulty)

What is the exact output of the following code snippets?

  1. Basic:

    python

    text = "one,two,three,four"
    parts = text.split(',')
    lengths = [len(p) for p in parts]
    print(lengths)
  2. Intermediate:

    python

    nums = [1, 2, 3, 4, 5, 6]
    comp = [x**2 for x in nums if x % 2 == 0]
    print(comp)
  3. Intermediate:

    python

    words = ["cat", "dog", "tiger", "lion"]
    result = [w.upper() if len(w) > 3 else w for w in words]
    print(result)
  4. Advanced:

    python

    text = "a b c"
    list1 = text.split()
    list2 = text.split(' ')
    list3 = text.split('b')
    print(f"list1: {list1}")
    print(f"list2: {list2}")
    print(f"list3: {list3}")
  5. Advanced:

    python

    data = ["1,2", "3,4", "5,6"]
    result = [int(num) for item in data for num in item.split(',') if int(num) % 2 != 0]
    print(result)
  6. Expert:

    python

    sentence = "hello world hello"
    words = sentence.split()
    comprehension = [word for i, word in enumerate(words) if word not in words[:i]]
    print(comprehension)
    
    words.append('world')
    comprehension2 = [word for i, word in enumerate(words) if word not in words[:i]]
    print(comprehension2)

Subtopic 4: enumerate(), Accessing Nested/2D Lists

Code Writing Questions (Increasing Difficulty)
  1. Basic: Create a list fruits = ["apple", "banana", "cherry"]. Use enumerate() to print each fruit with its index, starting from 1. The output should be "1: apple", "2: banana", etc.

  2. Intermediate: You have a 2D list representing a tic-tac-toe board:
    board = [['X', 'O', ' '], [' ', 'X', 'O'], ['O', ' ', 'X']]. Write code to print the element in the second row and third column (remember indexing starts at 0).

  3. Intermediate: Given the same board, write a function get_row(board, row_index) that returns a specific row, and get_column(board, col_index) that returns a specific column as a list.

  4. Advanced: Use nested loops and enumerate() to print a 3x3 matrix (like the board above) in a nice grid format. For the board above, print:

    text

    X | O |
    --------
      | X | O
    --------
    O |   | X
  5. Advanced: You have a list of lists: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]. Write a function diagonal_sum(matrix) that calculates the sum of the elements on the main diagonal (top-left to bottom-right). Assume the matrix is square.

  6. Expert: You have a list of lists where each inner list can have a different length: jagged = [[1, 2], [3, 4, 5], [6]]. Write a function find_all_positions(jagged_list, target) that returns a list of [row, col] indices where the target value is found. For example, find_all_positions(jagged, 4) should return [[1, 1]]. find_all_positions(jagged, 1) should return [[0, 0]]. If the target is not found, return an empty list.

Code Interpretation Questions (Increasing Difficulty)

What is the exact output of the following code snippets?

  1. Basic:

    python

    letters = ['a', 'b', 'c']
    for i, letter in enumerate(letters):
        print(f"{i}:{letter}")
  2. Intermediate:

    python

    matrix = [[1, 2], [3, 4], [5, 6]]
    print(matrix[1][0])
    print(matrix[-1][-1])
  3. Intermediate:

    python

    data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
    print(data[0][1][0])
  4. Advanced:

    python

    words = ["hello", "world"]
    enum_list = list(enumerate(words, start=2))
    print(enum_list)
  5. Advanced:

    python

    matrix = [[i + j for j in range(1, 4)] for i in range(0, 9, 3)]
    print(matrix)
    result = matrix[1][2] + matrix[2][1]
    print(result)
  6. Expert:

    python

    board = [[' ' for _ in range(3)] for _ in range(3)]
    board[0][1] = 'X'
    board[1][1] = 'O'
    board[2][0] = 'X'
    
    for i, row in enumerate(board):
        for j, cell in enumerate(row):
            if cell == 'X':
                print(f"X at ({i},{j})")
    
    print([(r, c) for r, row in enumerate(board) for c, val in enumerate(row) if val == 'O'])

Subtopic 5: Tuples (Creation, Access, Nesting, Packing/Unpacking)

Code Writing Questions (Increasing Difficulty)
  1. Basic: Create a tuple named colors containing the three primary colors: "red", "green", "blue". Then, print the second element of the tuple.

  2. Intermediate: You have a tuple point = (10, 20). Use tuple unpacking to assign the values to variables x and y. Then, swap the values of x and y in a single line of code and create a new tuple swapped_point from them.

  3. Intermediate: Create a nested tuple nested that represents a student's record: (student_id, (first_name, last_name), [grade1, grade2]). Choose your own data. Then, write code to access and print the student's last name.

  4. Advanced: You have a list of tuples, where each tuple is a (name, age): people = [("Alice", 30), ("Bob", 25), ("Charlie", 35)]. Write code using a list comprehension and tuple unpacking to create a new list containing only the names of people older than 28.

  5. Advanced: Write a function min_max_swap(numbers) that takes a tuple of numbers and returns a new tuple where the smallest and largest numbers have been swapped. For example, min_max_swap((5, 1, 9, 3, 7)) should return (5, 9, 1, 3, 7). Remember tuples are immutable.

  6. Expert: You are given a string "apple:1 banana:2 cherry:3". Use split(), tuple packing/unpacking, and list comprehension to create a list of tuples, where each tuple is (fruit_name, fruit_id_as_int). The final result should be [('apple', 1), ('banana', 2), ('cherry', 3)].

Code Interpretation Questions (Increasing Difficulty)

What is the exact output of the following code snippets?

  1. Basic:

    python

    my_tuple = (1, 2, 3)
    print(my_tuple[1])
    # my_tuple[1] = 99
    # print(my_tuple) # Uncommenting this line would cause what kind of error?
  2. Intermediate:

    python

    tuple_a = (1, 2)
    tuple_b = (1, 2)
    tuple_c = (1, [2, 3])
    
    print(tuple_a == tuple_b)
    print(tuple_a is tuple_b)
    # Is the line below valid? If not, why? If yes, what does it do?
    # tuple_c[1][0] = 99
    # print(tuple_c)
  3. Intermediate:

    python

    data = (10, 20, 30)
    a, b, c = data
    a = 99
    print(data)
    print(a, b, c)
  4. Advanced:

    python

    def get_coords():
        return (10, 20)
    
    x, y = get_coords()
    z = get_coords()
    print(x)
    print(z)
  5. Advanced:

    python

    my_tuple = (1, 2, 3, 4, 5)
    a, *b, c = my_tuple
    print(f"a: {a}")
    print(f"b: {b}")
    print(f"c: {c}")
  6. Expert:

    python

    list_of_tuples = [(i, i**2) for i in range(1, 4)]
    print(list_of_tuples)
    
    result = []
    for first, second in list_of_tuples:
        result.append((second, first))
    print(result)
    
    final_result = [(second, first) for (first, second) in list_of_tuples]
    print(final_result)

ANSWER KEY


Subtopic 1: Creating Lists, Slicing, len(), max(), sum(), shuffle()

Code Writing Solutions
  1. Basic:

    python

    colors = ["red", "green", "blue"]
    print(len(colors))  # Output: 3
  2. Intermediate:

    python

    data = "10,20,30,40,50"
    str_list = data.split(',')
    int_list = [int(num) for num in str_list]
    # Slice to exclude first and last: [20, 30, 40]
    result = sum(int_list[1:-1])
    print(result)  # Output: 90 (20+30+40)
  3. Intermediate:

    python

    # Start at 5, up to 33, step 2 -> 5,7,9,...,33
    original_list = list(range(5, 34, 2))
    # original_list = [5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33]
    first_three = original_list[:3]
    last_three = original_list[-3:]
    new_list = first_three + last_three
    print(new_list)  # Output: [5, 7, 9, 29, 31, 33]
  4. Advanced:

    python

    import random
    
    def list_manipulator(input_list):
        # (a) Create a shuffled copy
        shuffled = input_list[:]  # Create a copy
        random.shuffle(shuffled)
    
        # (b) Find max in original
        max_value = max(input_list)
    
        # (c) Find index of that max value in shuffled list
        max_index_in_shuffled = shuffled.index(max_value)
    
        return max_index_in_shuffled
    
    # Example usage
    my_nums = [10, 45, 22, 89, 33]
    # random.seed(42) # Optional: for testing predictable output
    result_index = list_manipulator(my_nums)
    print(f"Original: {my_nums}")
    print(f"Index of max in shuffled list: {result_index}")
  5. Advanced:

    python

    words = ["apple", "banana", "cherry", "date"]
    new_list = [[len(word), word] for word in words if len(word) > 5]
    print(new_list)  # Output: [[6, 'banana'], [6, 'cherry']]
  6. Expert:

    python

    # Generate odds from 1 to 9, then odds from 19 down to 11
    result = [i for i in range(1, 10, 2)] + [i for i in range(19, 10, -2)]
    print(result)  # Output: [1, 3, 5, 7, 9, 19, 17, 15, 13, 11]
Code Interpretation Answers
  1. Output: 6 (Last element 5 + first element 1)

  2. Output: [20, 30, 40, 60] (my_list[1:4] = [20,30,40]; my_list[5:] = [60]; concatenated)

  3. Output:

    text

    [1, 2, 3, 4, 5]
    [2, 99, 4]

    (Slicing creates a new list; modifying the slice does not affect the original)

  4. Output: [3, 4] (Elements that remained in the same position after shuffle: index 2=3, index 3=4)

  5. Output: [1, 3, 5] - [5, 3, 1] ([::2] = every 2nd from start; [-2::-2] = from index -2 backwards every 2nd)

  6. Output:

    text

    original: [1, 88, 3, 4, 5]
    a: [99, 3, 4]
    b: [1, 88, 3, 4, 5]
    c: [1, 2, 77, 4, 5]

Subtopic 2: Comparing Lists, append(), extend(), insert()

Code Writing Solutions
  1. Basic:

    python

    list_a = [1, 2, 3]
    list_a.append(4)
    print(list_a)  # Output: [1, 2, 3, 4]
  2. Intermediate:

    python

    list1 = [1, 2, 3]
    list2 = [1, 2, 3]
    
    if list1 == list2:
        print("Lists are equal")
    else:
        print("Lists are different")
    # Output: "Lists are equal"
  3. Intermediate:

    python

    tasks = ["write report"]
    # Use extend() to add multiple elements
    tasks.extend(["email client", "review code"])
    print(tasks)  # Output: ["write report", "email client", "review code"]
  4. Advanced:

    python

    names = ["Alice", "Charlie", "David"]
    name_to_insert = "Bob"
    
    # Find correct index to maintain alphabetical order
    for i in range(len(names)):
        if name_to_insert < names[i]:
            names.insert(i, name_to_insert)
            break
    else:  # If name is greater than all existing names, append at the end
        names.append(name_to_insert)
    
    print(names)  # Output: ['Alice', 'Bob', 'Charlie', 'David']
  5. Advanced:

    python

    def custom_extend(target_list, source_list):
        for item in source_list:
            target_list.append(item)
    
    # Example usage
    list_a = [1, 2, 3]
    list_b = [4, 5, 6]
    custom_extend(list_a, list_b)
    print(list_a)  # Output: [1, 2, 3, 4, 5, 6]
  6. Expert:

    python

    nums = [10, 20, 30, 40, 50]
    
    # Insert from the end to avoid index shifting issues
    for i in range(len(nums)-1, 0, -1):
        avg = (nums[i] + nums[i-1]) / 2
        nums.insert(i, avg)
    
    print(nums)  # Output: [10, 15.0, 20, 25.0, 30, 35.0, 40, 45.0, 50]
Code Interpretation Answers
  1. Output:

    text

    True
    False
    True
  2. Output: [1, 2, 3, [4, 5, 6]] (append() adds the entire list as one element)

  3. Output: [1, 2, 3, 4, 5, 6] (extend() adds each element individually)

  4. Output:

    text

    [1, 2, 4, 3]
    None

    (pop() returns 4, insert() modifies in-place and returns None)

  5. Output:

    text

    list_a: [10, 20, 30]
    list_b: [40, 10, 20, 30]
  6. Output:

    text

    a: [1, 2, 3, 5, 8]
    temp: [1, 2, 3, 5, 8]
    b: [4, 5, 6]
    c: [7, 8, 9]

Subtopic 3: Functions on Lists (split(), List Comprehensions)

Code Writing Solutions
  1. Basic:

    python

    sentence = "the quick brown fox"
    words = sentence.split()
    word_lengths = [len(word) for word in words]
    print(word_lengths)  # Output: [3, 5, 5, 3]
  2. Intermediate:

    python

    data = "name:John,age:30,city:NYC"
    pairs = data.split(',')
    result = [pair.split(':') for pair in pairs]
    print(result)  # Output: [['name', 'John'], ['age', '30'], ['city', 'NYC']]
  3. Intermediate:

    python

    squares_of_evens = [x**2 for x in range(1, 21) if x % 2 == 0]
    print(squares_of_evens)  # Output: [4, 16, 36, 64, 100, 144, 196, 256, 324, 400]
  4. Advanced:

    python

    def process_scores(scores):
        score_list = [int(score) for score in scores.split(',')]
        return [score if score >= 40 else "FAIL" for score in score_list]
    
    result = process_scores("45,67,89,12,90,33")
    print(result)  # Output: [45, 67, 89, 'FAIL', 90, 'FAIL']
  5. Advanced:

    python

    text = "Hello world, how are you?"
    words = text.split()
    filtered_words = [word for word in words if 'o' not in word]
    print(filtered_words)  # Output: ['Hello', 'are', 'you?']
    # Note: 'Hello' has 'o', so it's excluded. 'world,' has 'o', excluded. 'how' has 'o', excluded.
  6. Expert:

    python

    text = "apple banana apple cherry date banana apple"
    words = text.split()
    
    # Count frequencies
    freq_dict = {}
    for word in words:
        freq_dict[word] = freq_dict.get(word, 0) + 1
    
    # Sort by frequency (descending) then alphabetically
    unique_sorted = sorted(freq_dict.keys(), key=lambda w: (-freq_dict[w], w))
    print(unique_sorted)  # Output: ['apple', 'banana', 'cherry', 'date']
Code Interpretation Answers
  1. Output: [3, 3, 5, 4]

  2. Output: [4, 16, 36]

  3. Output: ['cat', 'dog', 'TIGER', 'LION']

  4. Output:

    text

    list1: ['a', 'b', 'c']
    list2: ['a', 'b', 'c']
    list3: ['a ', ' c']
  5. Output: [1, 3, 5]

  6. Output:

    text

    ['hello', 'world']
    ['hello', 'world']

Subtopic 4: enumerate(), Accessing Nested/2D Lists

Code Writing Solutions
  1. Basic:

    python

    fruits = ["apple", "banana", "cherry"]
    for index, fruit in enumerate(fruits, start=1):
        print(f"{index}: {fruit}")
    # Output:
    # 1: apple
    # 2: banana
    # 3: cherry
  2. Intermediate:

    python

    board = [['X', 'O', ' '], [' ', 'X', 'O'], ['O', ' ', 'X']]
    # Second row (index 1), third column (index 2)
    element = board[1][2]
    print(element)  # Output: 'O'
  3. Intermediate:

    python

    board = [['X', 'O', ' '], [' ', 'X', 'O'], ['O', ' ', 'X']]
    
    def get_row(board, row_index):
        return board[row_index]
    
    def get_column(board, col_index):
        return [row[col_index] for row in board]
    
    print(get_row(board, 0))      # Output: ['X', 'O', ' ']
    print(get_column(board, 1))    # Output: ['O', 'X', ' ']
  4. Advanced:

    python

    board = [['X', 'O', ' '], [' ', 'X', 'O'], ['O', ' ', 'X']]
    
    for i, row in enumerate(board):
        print(' | '.join(cell if cell != ' ' else ' ' for cell in row))
        if i < len(board) - 1:
            print('---------')
    # Output:
    # X | O |  
    # ---------
    #   | X | O
    # ---------
    # O |   | X
  5. Advanced:

    python

    matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    
    def diagonal_sum(matrix):
        total = 0
        for i in range(len(matrix)):
            total += matrix[i][i]
        return total
    
    print(diagonal_sum(matrix))  # Output: 15 (1 + 5 + 9)
  6. Expert:

    python

    jagged = [[1, 2], [3, 4, 5], [6]]
    
    def find_all_positions(jagged_list, target):
        positions = []
        for i in range(len(jagged_list)):
            for j in range(len(jagged_list[i])):
                if jagged_list[i][j] == target:
                    positions.append([i, j])
        return positions
    
    print(find_all_positions(jagged, 4))  # Output: [[1, 1]]
    print(find_all_positions(jagged, 1))  # Output: [[0, 0]]
    print(find_all_positions(jagged, 7))  # Output: []
Code Interpretation Answers
  1. Output:

    text

    0:a
    1:b
    2:c
  2. Output:

    text

    3
    6
  3. Output: 3

  4. Output: [(2, 'hello'), (3, 'world')]

  5. Output:

    text

    [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    14
  6. Output:

    text

    X at (0,1)
    X at (2,0)
    [(1, 1)]

Subtopic 5: Tuples (Creation, Access, Nesting, Packing/Unpacking)

Code Writing Solutions
  1. Basic:

    python

    colors = ("red", "green", "blue")
    print(colors[1])  # Output: green
  2. Intermediate:

    python

    point = (10, 20)
    x, y = point  # Unpacking
    x, y = y, x  # Swap in one line
    swapped_point = (x, y)
    print(swapped_point)  # Output: (20, 10)
  3. Intermediate:

    python

    nested = (101, ("John", "Smith"), [85, 92])
    # Access last name: first index 1 (the inner tuple), then index 1 (the last name)
    last_name = nested[1][1]
    print(last_name)  # Output: Smith
  4. Advanced:

    python

    people = [("Alice", 30), ("Bob", 25), ("Charlie", 35)]
    names_over_28 = [name for name, age in people if age > 28]
    print(names_over_28)  # Output: ['Alice', 'Charlie']
  5. Advanced:

    python

    def min_max_swap(numbers):
        num_list = list(numbers)  # Convert to list to modify
        min_val = min(num_list)
        max_val = max(num_list)
        min_index = num_list.index(min_val)
        max_index = num_list.index(max_val)
        # Swap
        num_list[min_index], num_list[max_index] = num_list[max_index], num_list[min_index]
        return tuple(num_list)
    
    result = min_max_swap((5, 1, 9, 3, 7))
    print(result)  # Output: (5, 9, 1, 3, 7)
  6. Expert:

    python

    data = "apple:1 banana:2 cherry:3"
    # Split by space, then each item by colon, convert second part to int
    result = [(item.split(':')[0], int(item.split(':')[1])) for item in data.split()]
    print(result)  # Output: [('apple', 1), ('banana', 2), ('cherry', 3)]
Code Interpretation Answers
  1. Output: 2. Uncommenting causes TypeError: 'tuple' object does not support item assignment.

  2. Output:

    text

    True
    False

    Comment explanation: Yes, it's valid. The tuple contains a list which is mutable. tuple_c becomes (1, [99, 3]).

  3. Output:

    text

    (10, 20, 30)
    99 20 30
  4. Output:

    text

    10
    (10, 20)
  5. Output:

    text

    a: 1
    b: [2, 3, 4]
    c: 5
  6. Output:

    text

    [(1, 1), (2, 4), (3, 9)]
    [(1, 1), (4, 2), (9, 3)]
    [(1, 1), (4, 2), (9, 3)]

Final Tip: For each question you got wrong, trace through the code line by line on paper. This is the best way to train your brain to think like a Python interpreter. Good luck on your midterm! You've got this.