Complete the code to create a list of squares for numbers 1 to 5.
squares = [x[1]2 for x in range(1, 6)] print(squares)
The ** operator is used to raise a number to a power. Here, x**2 squares the number.
Complete the code to filter numbers greater than 3 from the list.
numbers = [1, 2, 3, 4, 5] greater_than_three = [n for n in numbers if n [1] 3] print(greater_than_three)
The operator > checks if a number is greater than another. Here, it filters numbers greater than 3.
Fix the error in the code to calculate the average of a list of numbers.
data = [10, 20, 30, 40] average = sum(data) [1] len(data) print(average)
To find the average, sum all numbers and divide by the count using /.
Fill both blanks to create a dictionary of word lengths for words longer than 3 letters.
words = ['apple', 'bat', 'carrot', 'dog'] lengths = {word: [1] for word in words if len(word) [2] 3} print(lengths)
word instead of len(word) will store the word itself, not its length.The dictionary comprehension maps each word to its length using len(word). The condition len(word) > 3 filters words longer than 3 letters.
Fill both blanks to create a dictionary with uppercase keys and values greater than 10.
data = {'a': 5, 'b': 15, 'c': 25}
result = {k[1]: v for k, v in data.items() if v [2] 10}
print(result)The dictionary comprehension starts with {. The keys are converted to uppercase using k.upper(). The condition v > 10 filters values greater than 10.