Python List Exercises with Solutions

These Python list exercises cover topics such as indexing, looping, list methods, comprehension, and list operations.

Example:

numbers = [10, 20, 30, 40] # Output: 100 

Solution:

total = sum(numbers)
print("Sum:", total)

 Exercise 2: Multiply All Items in the List

Problem: Multiply all the numbers in a list.

numbers = [2, 3, 4] # Output: 24 

Solution:

result = 1 for num in numbers:
    result *= num
print("Product:", result)

 Exercise 3: Find the Largest Number

Problem: Find the largest number in a list.

nums = [4, 78, 34, 90, 12] # Output: 90 

Solution:

print("Max:", max(nums))

Exercise 4: Count Occurrences

Problem: Count the number of times a specific element appears.

letters = ['a', 'b', 'a', 'c', 'a'] # Count 'a' → Output: 3 

Solution:

count = letters.count('a')
print("Count of 'a':", count)

 Exercise 5: Remove Duplicates

Problem: Remove duplicate values from a list.

items = [1, 2, 2, 3, 4, 4] # Output: [1, 2, 3, 4] 

Solution:

unique_items = list(set(items))
print(unique_items)

 Exercise 6: Reverse a List

mylist = [1, 2, 3, 4] # Output: [4, 3, 2, 1] 

Solution:

print(mylist[::-1])

 Exercise 7: List Comprehension – Squares of Even Numbers

nums = [1, 2, 3, 4, 5, 6] # Output: [4, 16, 36] 

Solution:

squares = [x**2 for x in nums if x % 2 == 0]
print(squares)

 Exercise 8: Merge Two Lists

a = [1, 2] b = [3, 4] # Output: [1, 2, 3, 4] 

Solution:

print(a + b)

Exercise 9: Filter Strings Longer Than 3 Characters

words = ['hi', 'hello', 'to', 'world'] # Output: ['hello', 'world'] 

Solution:

filtered = [w for w in words if len(w) > 3]
print(filtered)

Exercise 10: Replace List Element

Problem: Replace the second element in the list with 'replaced'.

mylist = ['a', 'b', 'c'] # Output: ['a', 'replaced', 'c'] 

Solution:

mylist[1] = 'replaced' print(mylist)