Chapter 3 Exercises

Comprehensive exercises covering all collection types in Python.

Ali Berro

By Ali Berro

15 min read Section
From: Python Fundamentals: From Zero to Hero

Chapter 3 Exercises

Comprehensive exercises covering lists, tuples, strings, dictionaries, sets, and frozen sets.

Exercises

Exercise 1: Access nested dictionary values

What is the correct way to get Ali’s age from the following dictionary?

students = {
1: {'name': 'Ali', 'age': 25, 'gender': 'male'},
2: {'name': 'Sara', 'age': 22, 'gender': 'female'},
}
Answer:

The correct way to access Ali’s age is:

students = {
1: {'name': 'Ali', 'age': 25, 'gender': 'male'},
2: {'name': 'Sara', 'age': 22, 'gender': 'female'},
}
# Access Ali's age
age = students[1]['age']
print(age) # 25

Explanation: First access the dictionary with key 1 using students[1], which returns {'name': 'Ali', 'age': 25, 'gender': 'male'}, then access the 'age' key from that nested dictionary using ['age'].

Exercise 2: Can lists be dictionary keys?

Can lists be used as keys in a dictionary? Explain your answer.

Answer:

No, lists cannot be used as dictionary keys.

Dictionary keys must be hashable (immutable). Lists are mutable and therefore unhashable, so they cannot be used as dictionary keys.

However:

  • Tuples can be dictionary keys (if all their elements are also hashable)
  • Frozen sets can be dictionary keys
  • Strings, numbers can be dictionary keys

Example:

# This will raise a TypeError
# d = {[1, 2]: "value"} # TypeError: unhashable type: 'list'
# But this works
d = {(1, 2): "value"} # Tuples are hashable
d = {frozenset([1, 2]): "value"} # Frozen sets are hashable

Exercise 3: Which operation is incorrect on a tuple?

Suppose t = (1, 2, 4, 3). Which of the following operations is incorrect?

  1. t[3] = 45
  2. print(t[3])
  3. print(max(t))
  4. print(len(t))

Choose the correct answer from the options above:

Answer:

Option 1: t[3] = 45 is incorrect.

Tuples are immutable, so you cannot modify their elements. This operation will raise a TypeError: 'tuple' object does not support item assignment.

The other operations are all valid:

  • print(t[3]) - Accesses element at index 3 (value: 3)
  • print(max(t)) - Finds maximum value (4)
  • print(len(t)) - Gets the length (4)

Exercise 4: Access nested dictionary and tuple values

How would you access the number 3 from the following dictionary?

D = {'H': 0, 'E': 1, 'L': {'L': (1, 2, 3)}}
Answer:

To access the number 3, first access the nested dictionary with key 'L', then access the tuple with key 'L', and finally access the element at index 2:

D = {'H': 0, 'E': 1, 'L': {'L': (1, 2, 3)}}
# Access the number 3
value = D['L']['L'][2]
print(value) # 3

Breaking it down:

  • D['L'] returns {'L': (1, 2, 3)}
  • D['L']['L'] returns (1, 2, 3)
  • D['L']['L'][2] returns 3 (the element at index 2)

Exercise 5: Append to a tuple in a dictionary

What code can be written to append the number 7 to the tuple (4, 5, 6) stored in the dictionary?

D = {1: (1, 2, 3), 2: (4, 5, 6)}
Answer:

Since tuples are immutable, you cannot modify them directly. You need to create a new tuple and assign it back to the dictionary:

D = {1: (1, 2, 3), 2: (4, 5, 6)}
# Create a new tuple by concatenating the existing tuple with (7,)
D[2] = D[2] + (7,)
print(D) # {1: (1, 2, 3), 2: (4, 5, 6, 7)}

Alternatively:

D = {1: (1, 2, 3), 2: (4, 5, 6)}
# Using tuple unpacking
D[2] = (*D[2], 7)
print(D) # {1: (1, 2, 3), 2: (4, 5, 6, 7)}

Exercise 6: Remove duplicate words from string

Write a program that reads a string s and removes all words that appear more than once, then prints the remaining words in the same order they appear in the string.

Remove Duplicate Words

Checks: 0 times
Answer:
s = input()
words = s.split()
for word in words:
if word.count(word) == 1:
print(word, end=" ")

Another solution:

s = input()
words = s.split()
seen = {}
for word in words:
seen[word] = seen.get(word, 0) + 1
for word, count in seen.items():
if count == 1:
print(word, end=" ")

Exercise 7: Add alternating numbers between words

Write a program that reads a string s and adds “1” and “2” alternating between words. For example, given “This is a big message”, the output should be “This1 2is1 2a1 2big1 2message”.

Alternating Numbers

Checks: 0 times
Answer:
s = input()
words = s.split()
print("1 2".join(words))

Exercise 8: What is the output of the string membership check?

What will be the output of the following code?

s = "Hello World"
for i in s:
if i in "hEllO woRLd":
print(i, end="")
  1. llo old
  2. Hello World
  3. hEllO woRLd
  4. ll od
  5. Nothing, it’s a trick question.

Choose the correct answer from the options above:

Answer:

The output is: llo old

Explanation:

  • The loop iterates through each character in "Hello World": 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'
  • For each character, it checks if it exists in "hEllO woRLd" (case-sensitive)
  • Characters that match: 'l', 'l', 'o', ' ', 'o', 'l', 'd'
  • Printed without newlines (due to end=""): llo old

Note: The membership check is case-sensitive, so 'H' (uppercase) is not in "hEllO woRLd" (which has lowercase 'h'), and 'e' (lowercase) is not in the string (which has uppercase 'E').

Exercise 9: Maximum sum of inner lists

Write a program that reads the number of lists n, then for each list reads its size and elements, and prints the maximum of the sums of all inner lists. For example, given [[1, 2, 3], [-1, 2], [-9], [4, 8]], the sums are 6, 1, -9, 12, and the maximum is 12.

Maximum Sum of Lists

Checks: 0 times
Answer:
n = int(input())
lists = []
for i in range(n):
size = int(input())
inner_list = []
for j in range(size):
inner_list.append(int(input()))
lists.append(inner_list)
if len(lists) > 0:
max_sum = sum(lists[0])
for inner_list in lists:
current_sum = sum(inner_list)
if current_sum > max_sum:
max_sum = current_sum
print(max_sum)
else:
print(0)

Exercise 10: Element-wise multiplication of two lists

Write a program that reads the size n, then reads n elements for list m, then reads n elements for list n, creates a new list r where each element at index i is equal to m[i] * n[i], and prints it.

Element-wise Multiplication

Checks: 0 times
Answer:
n = int(input())
m = []
for i in range(n):
m.append(int(input()))
n_list = []
for i in range(n):
n_list.append(int(input()))
r = []
for i in range(n):
r.append(m[i] * n_list[i])
print(r)

Exercise 11: Convert list of strings to dictionary

Write a program that reads the number of strings n, then reads n strings, and creates a dictionary where keys are the strings and values are their lengths. Print the dictionary.

Strings to Dictionary

Checks: 0 times
Answer:
n = int(input())
d = {}
for i in range(n):
s = input()
d[s] = len(s)
print(d)

Exercise 12: Find common elements between list and tuple

Write a program that reads the size of a list, then reads its elements, then reads the size of a tuple, then reads its elements, and prints all elements that appear in both the list and the tuple.

Common Elements List and Tuple

Checks: 0 times
Answer:
n1 = int(input())
list1 = []
for i in range(n1):
list1.append(input())
n2 = int(input())
tuple1 = []
for i in range(n2):
tuple1.append(input())
tuple1 = tuple(tuple1)
common = []
for item in list1:
if item in tuple1 and item not in common:
common.append(item)
for item in common:
print(item)

Exercise 13: Count word frequency using dictionary

Write a program that reads a string and counts the frequency of each word using a dictionary. Print each word and its count on a separate line, in the order words first appear.

Word Frequency

Checks: 0 times
Answer:
text = input()
words = text.split()
freq = {}
order = []
for word in words:
if word not in freq:
freq[word] = 0
order.append(word)
freq[word] += 1
for word in order:
print(f"{word} {freq[word]}")

Exercise 14: Convert string to list of characters and back

Write a program that reads a string, converts it to a list of characters, modifies the list (reverses it), then converts it back to a string and prints it.

String to List and Back

Checks: 0 times
Answer:
s = input()
char_list = list(s)
char_list.reverse()
result = "".join(char_list)
print(result)

Exercise 15: Find elements in list but not in set

Write a program that reads the size of a list, then reads its elements, then reads the size of a set, then reads its elements, and prints all elements that are in the list but not in the set (in the order they appear in the list).

List Minus Set

Checks: 0 times
Answer:
n1 = int(input())
list1 = []
for i in range(n1):
list1.append(input())
n2 = int(input())
set1 = set()
for i in range(n2):
set1.add(input())
for item in list1:
if item not in set1:
print(item)

Exercise 16: Create dictionary from tuple of pairs

Write a program that reads the number of pairs n, then for each pair reads two values, creates a tuple for each pair, stores them in a list, and then creates a dictionary from the list of tuples. Print the dictionary.

Dictionary from Tuple Pairs

Checks: 0 times
Answer:
n = int(input())
pairs = []
for i in range(n):
key = input()
value = input()
pairs.append((key, value))
d = dict(pairs)
print(d)

Exercise 17: Check if string contains only unique characters

Write a program that reads a string and prints "Yes" if all characters in the string are unique (no duplicates), otherwise prints "No".

Unique Characters Check

Checks: 0 times
Answer:
s = input()
char_set = set(s)
if len(s) == len(char_set):
print("Yes")
else:
print("No")

Exercise 18: Merge list and tuple into dictionary

Write a program that reads the size n, then reads n keys, then reads n values, creates a list of keys and a tuple of values, and creates a dictionary from them. Print the dictionary.

List and Tuple to Dictionary

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())
values = tuple(values)
d = {}
for i in range(n):
d[keys[i]] = values[i]
print(d)

Exercise 19: Find longest word in a string

Write a program that reads a string and finds the longest word in it. If there are multiple words with the same maximum length, print the first one.

Longest Word

Checks: 0 times
Answer:
s = input()
words = s.split()
longest = words[0]
for word in words:
if len(word) > len(longest):
longest = word
print(longest)

Exercise 20: Convert dictionary values to tuple

Write a program that reads the number of key-value pairs n, then reads each key-value pair, creates a dictionary, and converts all values to a tuple. Print the tuple.

Dictionary Values to Tuple

Checks: 0 times
Answer:
n = int(input())
d = {}
for i in range(n):
key = input()
value = input()
d[key] = value
values_tuple = tuple(d.values())
print(values_tuple)

Exercise 21: Check if all list elements are in set

Write a program that reads the size of a list, then reads its elements, then reads the size of a set, then reads its elements, and prints "Yes" if all elements in the list are also in the set, otherwise prints "No".

List Subset of Set

Checks: 0 times
Answer:
n1 = int(input())
list1 = []
for i in range(n1):
list1.append(input())
n2 = int(input())
set1 = set()
for i in range(n2):
set1.add(input())
all_in_set = True
for item in list1:
if item not in set1:
all_in_set = False
break
if all_in_set:
print("Yes")
else:
print("No")

Exercise 22: Dictionary with tuple keys

Write a program that reads the number of entries n, then for each entry reads two numbers representing a coordinate pair, creates a tuple from the pair, and uses it as a key in a dictionary with value "point_{x}_{y}". Print the dictionary.

Dictionary with Tuple Keys

Checks: 0 times
Answer:
n = int(input())
d = {}
for i in range(n):
x = int(input())
y = int(input())
key = (x, y)
d[key] = f"point_{x}_{y}"
print(d)

Exercise 23: Check if string is anagram

Write a program that reads two strings and prints "Yes" if they are anagrams (contain the same characters in any order), otherwise prints "No".

Anagram Check

Checks: 0 times
Answer:
s1 = input()
s2 = input()
# Remove spaces and convert to lowercase for comparison
s1_chars = sorted(s1.replace(" ", "").lower())
s2_chars = sorted(s2.replace(" ", "").lower())
if s1_chars == s2_chars:
print("Yes")
else:
print("No")

Course Progress

Section 30 of 61

Back to Course