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)
Basic: Create a list named
colorscontaining the strings "red", "green", and "blue". Then, print the length of the list.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.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.
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 needrandom.shuffleandlist.index()).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']].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?
Basic:
python
my_list = [1, 2, 3, 4, 5] print(my_list[-1] + my_list[0])Intermediate:
python
my_list = [10, 20, 30, 40, 50, 60] result = my_list[1:4] + my_list[5:] print(result)Intermediate:
python
my_list = [1, 2, 3, 4, 5] sliced = my_list[1:4] sliced[1] = 99 print(my_list) print(sliced)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)Advanced:
python
my_list = [1, 2, 3, 4, 5, 6] slice1 = my_list[::2] slice2 = my_list[-2::-2] print(f"{slice1} - {slice2}")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)
Basic: Create a list
list_a = [1, 2, 3]. Use a method to add the single number4to the end oflist_a. Print the result.Intermediate: Create two lists:
list1 = [1, 2, 3]andlist2 = [1, 2, 3]. Write anifstatement that prints "Lists are equal" if they have the same elements in the same order, and "Lists are different" otherwise.Intermediate: Create a list
tasks = ["write report"]. Use the most appropriate method to add the elements"email client"and"review code"totasksso that the final list is["write report", "email client", "review code"].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 usingsort()or creating a new list.Advanced: Write a function
custom_extend(target_list, source_list)that manually replicates the behavior oftarget_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.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?
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)Intermediate:
python
list1 = [1, 2, 3] list2 = [4, 5, 6] list1.append(list2) print(list1)Intermediate:
python
list1 = [1, 2, 3] list2 = [4, 5, 6] list1.extend(list2) print(list1)Advanced:
python
original = [1, 2, 3, 4] result = original.insert(2, original.pop()) print(original) print(result)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}")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)
Basic: Given the string
sentence = "the quick brown fox", use thesplit()function to create a list of the words. Then, use a list comprehension to create a new list containing the lengths of each word.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']].Intermediate: Use a single list comprehension to generate a list of the squares of even numbers from 1 to 20.
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 anif-elseto 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'].Advanced: You have a string
text = "Hello world, how are you?". Usesplit()and list comprehension to create a list of words, but exclude any word that contains the letter 'o'. Print the result.Expert: You are given a string
"apple banana apple cherry date banana apple". Write code (potentially usingsplit(), 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?
Basic:
python
text = "one,two,three,four" parts = text.split(',') lengths = [len(p) for p in parts] print(lengths)Intermediate:
python
nums = [1, 2, 3, 4, 5, 6] comp = [x**2 for x in nums if x % 2 == 0] print(comp)Intermediate:
python
words = ["cat", "dog", "tiger", "lion"] result = [w.upper() if len(w) > 3 else w for w in words] print(result)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}")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)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)
Basic: Create a list
fruits = ["apple", "banana", "cherry"]. Useenumerate()to print each fruit with its index, starting from 1. The output should be "1: apple", "2: banana", etc.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).Intermediate: Given the same
board, write a functionget_row(board, row_index)that returns a specific row, andget_column(board, col_index)that returns a specific column as a list.Advanced: Use nested loops and
enumerate()to print a 3x3 matrix (like the board above) in a nice grid format. For theboardabove, print:text
X | O | -------- | X | O -------- O | | XAdvanced: You have a list of lists:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]. Write a functiondiagonal_sum(matrix)that calculates the sum of the elements on the main diagonal (top-left to bottom-right). Assume the matrix is square.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 functionfind_all_positions(jagged_list, target)that returns a list of[row, col]indices where thetargetvalue 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?
Basic:
python
letters = ['a', 'b', 'c'] for i, letter in enumerate(letters): print(f"{i}:{letter}")Intermediate:
python
matrix = [[1, 2], [3, 4], [5, 6]] print(matrix[1][0]) print(matrix[-1][-1])Intermediate:
python
data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] print(data[0][1][0])Advanced:
python
words = ["hello", "world"] enum_list = list(enumerate(words, start=2)) print(enum_list)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)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)
Basic: Create a tuple named
colorscontaining the three primary colors: "red", "green", "blue". Then, print the second element of the tuple.Intermediate: You have a tuple
point = (10, 20). Use tuple unpacking to assign the values to variablesxandy. Then, swap the values ofxandyin a single line of code and create a new tupleswapped_pointfrom them.Intermediate: Create a nested tuple
nestedthat 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.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.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.Expert: You are given a string
"apple:1 banana:2 cherry:3". Usesplit(), 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?
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?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)Intermediate:
python
data = (10, 20, 30) a, b, c = data a = 99 print(data) print(a, b, c)Advanced:
python
def get_coords(): return (10, 20) x, y = get_coords() z = get_coords() print(x) print(z)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}")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
Basic:
python
colors = ["red", "green", "blue"] print(len(colors)) # Output: 3Intermediate:
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)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]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}")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']]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
Output:
6(Last element5+ first element1)Output:
[20, 30, 40, 60](my_list[1:4]=[20,30,40];my_list[5:]=[60]; concatenated)Output:
text
[1, 2, 3, 4, 5] [2, 99, 4](Slicing creates a new list; modifying the slice does not affect the original)
Output:
[3, 4](Elements that remained in the same position after shuffle: index 2=3, index 3=4)Output:
[1, 3, 5] - [5, 3, 1]([::2]= every 2nd from start;[-2::-2]= from index -2 backwards every 2nd)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
Basic:
python
list_a = [1, 2, 3] list_a.append(4) print(list_a) # Output: [1, 2, 3, 4]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"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"]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']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]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
Output:
text
True False TrueOutput:
[1, 2, 3, [4, 5, 6]](append()adds the entire list as one element)Output:
[1, 2, 3, 4, 5, 6](extend()adds each element individually)Output:
text
[1, 2, 4, 3] None(
pop()returns 4,insert()modifies in-place and returnsNone)Output:
text
list_a: [10, 20, 30] list_b: [40, 10, 20, 30]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
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]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']]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]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']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.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
Output:
[3, 3, 5, 4]Output:
[4, 16, 36]Output:
['cat', 'dog', 'TIGER', 'LION']Output:
text
list1: ['a', 'b', 'c'] list2: ['a', 'b', 'c'] list3: ['a ', ' c']Output:
[1, 3, 5]Output:
text
['hello', 'world'] ['hello', 'world']
Subtopic 4: enumerate(), Accessing Nested/2D Lists
Code Writing Solutions
Basic:
python
fruits = ["apple", "banana", "cherry"] for index, fruit in enumerate(fruits, start=1): print(f"{index}: {fruit}") # Output: # 1: apple # 2: banana # 3: cherryIntermediate:
python
board = [['X', 'O', ' '], [' ', 'X', 'O'], ['O', ' ', 'X']] # Second row (index 1), third column (index 2) element = board[1][2] print(element) # Output: 'O'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', ' ']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 | | XAdvanced:
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)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
Output:
text
0:a 1:b 2:cOutput:
text
3 6Output:
3Output:
[(2, 'hello'), (3, 'world')]Output:
text
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] 14Output:
text
X at (0,1) X at (2,0) [(1, 1)]
Subtopic 5: Tuples (Creation, Access, Nesting, Packing/Unpacking)
Code Writing Solutions
Basic:
python
colors = ("red", "green", "blue") print(colors[1]) # Output: greenIntermediate:
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)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: SmithAdvanced:
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']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)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
Output:
2. Uncommenting causesTypeError: 'tuple' object does not support item assignment.Output:
text
True FalseComment explanation: Yes, it's valid. The tuple contains a list which is mutable.
tuple_cbecomes(1, [99, 3]).Output:
text
(10, 20, 30) 99 20 30Output:
text
10 (10, 20)Output:
text
a: 1 b: [2, 3, 4] c: 5Output:
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.