Complete the code to create a generator expression that saves memory.
squares = (x[1]2 for x in range(1, 6)) print(list(squares))
The ** operator is used to calculate powers. Here, x**2 computes squares efficiently.
Complete the code to convert a list to a generator expression for memory efficiency.
numbers = [1, 2, 3, 4, 5] generator = (num for num [1] numbers) print(list(generator))
The keyword in is used to iterate over elements in a list or iterable in Python.
Fix the error in the code to create a memory-efficient data filter using a generator.
data = [10, 15, 20, 25, 30] filtered = (x for x in data if x [1] 20) print(list(filtered))
The code filters values greater than 20, so the correct operator is >.
Fill both blanks to create a dictionary comprehension that stores word lengths only for words longer than 3 letters.
words = ['cat', 'house', 'dog', 'elephant'] lengths = {word: [1] for word in words if len(word) [2] 3} print(lengths)
The dictionary stores the length of each word, so len(word) is used. The condition keeps words longer than 3 letters, so > is correct.
Fill all three blanks to create a dictionary comprehension that stores uppercase words as keys and their lengths as values, only for words longer than 4 letters.
words = ['apple', 'bat', 'carrot', 'dog'] result = { [1]: [2] for w in words if len(w) [3] 4 } print(result)
The keys are uppercase words (w.upper()), the values are their lengths (len(w)), and the filter keeps words longer than 4 letters (>).