Chapter 5 Exercises

Comprehensive exercises covering comprehensions in Python.

Chapter 5 Exercises

Comprehensive exercises covering comprehensions in Python, sorted from easiest to hardest.

Exercises

Exercise 1: List of Ones

Create a function called create_ones that takes an integer n and returns a list of n ones using list comprehension.

List of Ones

Checks: 0 times
Answer:
def create_ones(n):
return [1 for _ in range(n)]
n = int(input())
result = create_ones(n)
print(result)

Exercise 2: Clone List

Write a function called clone_list that takes a list and returns a new list (clone) using list comprehension.

Clone List

Checks: 0 times
Answer:
def clone_list(lst):
return [item for item in lst]

Exercise 3: Squares with List Comprehension

Use list comprehension to create a list of squares of numbers from 0 to 9.

Squares with List Comprehension

Checks: 0 times
Answer:
squares = [n * n for n in range(10)]
print(squares)

Exercise 4: Even Numbers with Condition

Use list comprehension to create a list of even numbers from 0 to 20.

Even Numbers with Condition

Checks: 0 times
Answer:
evens = [n for n in range(21) if n % 2 == 0]
print(evens)

Exercise 5: Dictionary from Lists

Use dictionary comprehension to create a dictionary mapping numbers from 0 to 9 to their squares.

Dictionary from Lists

Checks: 0 times
Answer:
squares_dict = {n: n * n for n in range(10)}
print(squares_dict)

Exercise 6: Set of Unique Squares

Use set comprehension to create a set of squares of numbers from -5 to 5. Note how duplicates are automatically removed.

Set of Unique Squares

Checks: 0 times
Answer:
unique_squares = {n * n for n in range(-5, 6)}
print(unique_squares)

Exercise 7: Filtered Dictionary

Use dictionary comprehension with a condition to create a dictionary mapping even numbers from 0 to 20 to their halves.

Filtered Dictionary

Checks: 0 times
Answer:
halves = {n: n // 2 for n in range(21) if n % 2 == 0}
print(halves)

Exercise 8: Nested List Comprehension

Use nested list comprehension to create a multiplication table (list of lists) for numbers 1 to 5.

Nested List Comprehension

Checks: 0 times
Answer:
table = [[i * j for j in range(1, 6)] for i in range(1, 6)]
print(table)

Exercise 9: Conditional Expression in Comprehension

Use list comprehension with a conditional expression to create a list where even numbers are kept as-is and odd numbers are squared.

Conditional Expression in Comprehension

Checks: 0 times
Answer:
result = [n if n % 2 == 0 else n * n for n in range(10)]
print(result)

Exercise 10: String Lengths Dictionary

Given a list of strings, use dictionary comprehension to create a dictionary mapping each string to its length.

String Lengths Dictionary

Checks: 0 times
Answer:
n = int(input())
words = []
for i in range(n):
words.append(input())
lengths = {word: len(word) for word in words}
print(lengths)

Exercise 11: Flatten Nested List

Write a function called flatten that takes a list of lists and returns a flattened list using nested list comprehension.

Flatten Nested List

Checks: 0 times
Answer:
def flatten(nested_list):
return [item for sublist in nested_list for item in sublist]

Exercise 12: Prime Numbers with Comprehension

Use list comprehension to create a list of prime numbers less than 50. A prime number is only divisible by 1 and itself. Use a helper function is_prime to check if a number is prime.

Prime Numbers with Comprehension

Checks: 0 times
Answer:
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
primes = [n for n in range(2, 50) if is_prime(n)]
print(primes)

Exercise 13: Character Frequency Dictionary

Use dictionary comprehension to create a dictionary that counts the frequency of each character in a string. Read a string from input.

Character Frequency Dictionary

Checks: 0 times
Answer:
text = input()
frequency = {char: text.count(char) for char in set(text)}
print(frequency)

Exercise 14: Matrix Transpose

Use nested list comprehension to transpose a matrix (swap rows and columns). Read the number of rows, then read each row.

Matrix Transpose

Checks: 0 times
Answer:
rows = int(input())
cols = int(input())
matrix = []
for i in range(rows):
row = []
for j in range(cols):
row.append(int(input()))
matrix.append(row)
transposed = [[matrix[j][i] for j in range(rows)] for i in range(cols)]
print(transposed)

Exercise 15: Comprehension Code Analysis

What is the output of the following code? Analyze each comprehension step by step.

A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
A1 = range(10)
A2 = sorted([i for i in A1 if i in A0])
A3 = sorted([A0[s] for s in A0])
A4 = [i for i in A1 if i in A3]
A5 = {i : i * i for i in A1}
A6 = [[i , i * i] for i in A1]
print(A0, A1, A2, A3, A4, A5, A6)
Answer:
A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5))) # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
A1 = range(10) # range(0, 10)
A2 = sorted([i for i in A1 if i in A0]) # [] - checks if numbers 0-9 are keys in A0 (they're not)
A3 = sorted([A0[s] for s in A0]) # [1, 2, 3, 4, 5] - values from A0
A4 = [i for i in A1 if i in A3] # [1, 2, 3, 4, 5] - numbers in A1 that are in A3
A5 = {i : i * i for i in A1} # {0: 0, 1: 1, 2: 4, ..., 9: 81}
A6 = [[i , i * i] for i in A1] # [[0, 0], [1, 1], [2, 4], ..., [9, 81]]
# Output:
# {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} range(0, 10) [] [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]

Exercise 16: Cartesian Product

Write a function called cartesian_product that takes two lists and returns the Cartesian product (all possible pairs) using nested list comprehension.

Cartesian Product

Checks: 0 times
Answer:
def cartesian_product(list1, list2):
return [(x, y) for x in list1 for y in list2]

Exercise 17: Dictionary from Two Lists

Use dictionary comprehension to create a dictionary from two lists: one for keys and one for values. Read the number of elements, then read keys and values.

Dictionary from Two Lists

Checks: 0 times
Answer:
n = int(input())
keys = []
for i in range(n):
keys.append(input())
values = []
for i in range(n):
values.append(input())
result = {keys[i]: values[i] for i in range(n)}
print(result)

Exercise 18: Filtered Set Comprehension

Use set comprehension to create a set of numbers from 1 to 100 that are divisible by both 3 and 5.

Filtered Set Comprehension

Checks: 0 times
Answer:
result = {n for n in range(1, 101) if n % 3 == 0 and n % 5 == 0}
print(result)

Exercise 19: Nested Dictionary Comprehension

Use nested dictionary comprehension to create a dictionary where keys are tuples (i, j) and values are i * j, for i and j from 1 to 3.

Nested Dictionary Comprehension

Checks: 0 times
Answer:
result = {(i, j): i * j for i in range(1, 4) for j in range(1, 4)}
print(result)

Exercise 20: Complex Nested Comprehension

Use nested list comprehension to create a list of lists where each inner list contains numbers from 1 to n, for n from 1 to 5.

Complex Nested Comprehension

Checks: 0 times
Answer:
result = [[j for j in range(1, i + 1)] for i in range(1, 6)]
print(result)

Exercise 21: Conditional Dictionary Values

Use dictionary comprehension with a conditional expression to create a dictionary mapping numbers 1 to 10, where values are “even” for even numbers and “odd” for odd numbers.

Conditional Dictionary Values

Checks: 0 times
Answer:
result = {n: "even" if n % 2 == 0 else "odd" for n in range(1, 11)}
print(result)

Exercise 22: Multiple Conditions in Comprehension

Use list comprehension with multiple conditions to create a list of numbers from 1 to 50 that are divisible by 3 but not by 5.

Multiple Conditions in Comprehension

Checks: 0 times
Answer:
result = [n for n in range(1, 51) if n % 3 == 0 and n % 5 != 0]
print(result)

Exercise 23: Inverting Dictionary

Use dictionary comprehension to invert a dictionary (swap keys and values). If multiple keys have the same value, handle it appropriately. Read the number of entries, then read key-value pairs.

Inverting Dictionary

Checks: 0 times
Answer:
n = int(input())
original = {}
for i in range(n):
key = input()
value = input()
original[key] = value
inverted = {value: key for key, value in original.items()}
print(inverted)

Exercise 24: List of Dictionaries from Lists

Use list comprehension to create a list of dictionaries. Given lists of names and ages, create a list where each dictionary has ‘name’ and ‘age’ keys.

List of Dictionaries from Lists

Checks: 0 times
Answer:
n = int(input())
names = []
for i in range(n):
names.append(input())
ages = []
for i in range(n):
ages.append(input())
people = [{'name': names[i], 'age': ages[i]} for i in range(n)]
print(people)

Exercise 25: Nested Dictionary with Complex Sorting

Write a function process_students that takes a list of dictionaries where each dictionary has nested dictionaries (e.g., {'name': 'Alice', 'scores': {'math': 85, 'science': 90, 'english': 80}}). The function should use sorted() with a complex lambda key that sorts by the sum of all nested score values (descending), then by name (alphabetically). Return a dictionary comprehension that maps each name to their average score.

Nested Dictionary with Complex Sorting

Checks: 0 times
Answer:
def process_students(students):
sorted_students = sorted(students, key=lambda x: (-sum(x['scores'].values()), x['name']))
return {s['name']: sum(s['scores'].values()) / len(s['scores']) for s in sorted_students}

Exercise 26: List of Tuples with Tuple Keys in Dictionary

Write a function process_data that takes a list of tuples where each tuple contains (name, (x, y) coordinates, score). The function should use sorted() with a lambda key that sorts by the Euclidean distance from origin (x**2 + y**2)**0.5 (ascending), then by score (descending). Return a dictionary comprehension where keys are tuples (name, score) and values are the coordinates.

List of Tuples with Tuple Keys in Dictionary

Checks: 0 times
Answer:
def process_data(data):
sorted_data = sorted(data, key=lambda x: ((x[1][0]**2 + x[1][1]**2)**0.5, -x[2]))
return {(item[0], item[2]): item[1] for item in sorted_data}

Exercise 27: Nested Lists with Complex Mapping

Write a function process_nested that takes a nested list of lists where each inner list contains numbers. The function should use map() with a lambda to compute the sum of each inner list, then use filter() with a lambda to keep only sums greater than 10. Return a dictionary comprehension mapping each filtered sum to a tuple of (original_length, doubled_sum). You’ll need to track which list corresponds to which sum.

Nested Lists with Complex Mapping

Checks: 0 times
Answer:
def process_nested(nested):
sums = list(map(lambda lst: sum(lst), nested))
filtered = list(filter(lambda s: s > 10, sums))
sum_to_length = {sum(lst): len(lst) for lst in nested}
return {s: (sum_to_length[s], s * 2) for s in filtered}

Exercise 28: List of Dictionaries with Nested Lists

Write a function process_items that takes a list of dictionaries where each dictionary has a ‘name’ key and a ‘data’ key containing a nested list of numbers. The function should use sorted() with a lambda key that sorts by the maximum value in the nested list (descending), then by the length of the nested list (ascending), then by name (alphabetically). Return a dictionary comprehension mapping each name to a tuple of (max_value, sum_of_list).

List of Dictionaries with Nested Lists

Checks: 0 times
Answer:
def process_items(items):
sorted_items = sorted(items, key=lambda x: (-max(x['data']), len(x['data']), x['name']))
return {item['name']: (max(item['data']), sum(item['data'])) for item in sorted_items}

Exercise 29: Complex Nested Dictionary with Tuple Keys

Write a function process_data that takes a list of dictionaries with structure {'id': (x, y), 'values': [n1, n2, ...], 'meta': {'count': c, 'sum': s}}. The function should use sorted() with a lambda key that sorts by the product of tuple coordinates x * y (descending), then by the ‘count’ in meta (ascending). Return a dictionary comprehension where keys are tuples (id_tuple, max_value) and values are nested dictionaries with ‘avg’ and ‘total’ keys.

Complex Nested Dictionary with Tuple Keys

Checks: 0 times
Answer:
def process_data(data):
sorted_data = sorted(data, key=lambda x: (-(x['id'][0] * x['id'][1]), x['meta']['count']))
return {(item['id'], max(item['values'])): {'avg': sum(item['values']) / len(item['values']), 'total': item['meta']['sum']} for item in sorted_data}

Exercise 30: Ultimate Complex Structure with Weird Keys

Write a function process_complex that takes a list of dictionaries with structure {'key': (a, b, c), 'nested': {'list': [x, y, z], 'dict': {'p': p_val, 'q': q_val}}}. The function should use sorted() with a complex lambda key that sorts by a * b + c (descending), then by the sum of the nested list (ascending), then by p_val * q_val (descending). Return a dictionary comprehension where keys are tuples (key_tuple, nested_sum) and values are dictionaries with ‘product’ (p*q) and ‘list_max’ keys.

Ultimate Complex Structure with Weird Keys

Checks: 0 times
Answer:
def process_complex(data):
sorted_data = sorted(data, key=lambda x: (-(x['key'][0] * x['key'][1] + x['key'][2]), sum(x['nested']['list']), -(x['nested']['dict']['p'] * x['nested']['dict']['q'])))
return {(item['key'], sum(item['nested']['list'])): {'product': item['nested']['dict']['p'] * item['nested']['dict']['q'], 'list_max': max(item['nested']['list'])} for item in sorted_data}

Course Progress

Section 45 of 61

Back to Course