Python list is the most widely used data structure, and a good understanding of it is necessary. This Python list exercise aims to help developers learn and practice list operations.
This Python list exercise contains 23 coding questions, each with a provided solution. Practice and solve various list data structure-based programming challenges.
Questions cover the following list topics:
- list operations and manipulations
- list functions
- list slicing
- list comprehension
Let us know if you have any alternative solutions in the comment section below.
- Use Online Code Editor to solve exercise questions.
- Read the Complete guide on Python List to solve this exercise.
Table of contents
- Exercise 1: Perform Basic List Operations
- Exercise 2: Perform List Manipulation
- Exercise 3: Sum and average of all numbers in a list
- Exercise 4: Reverse a list
- Exercise 5: Turn every item of a list into its square
- Exercise 6: Find Maximum and Minimum
- Exercise 7: Count Occurrences
- Exercise 8: Sort a list of numbers
- Exercise 9: Create a copy of a list
- Exercise 10: Combine two lists
- Exercise 11: Remove empty strings from the list of strings
- Exercise 12: Remove Duplicates from list
- Exercise 13: Remove all occurrences of a specific item from a list
- Exercise 14: List Comprehension for Numbers
- Exercise 15: Access Nested Lists
- Exercise 16: Flatten Nested List
- Exercise 17: Concatenate two lists index-wise
- Exercise 18: Concatenate two lists in the following order
- Exercise 19: Iterate both lists simultaneously
- Exercise 21: Add new item to list after a specified item
- Exercise 22: Extend nested list by adding the sublist
- Exercise 23: Replace list’s item with new value if found
Exercise 1: Perform Basic List Operations
Given:
my_list = [10, 20, 30, 40, 50]
Code language: Python (python)
Perform following operations on given list
- Access Elements: Print the third element.
- List Length: Print the number of elements in the list
- Check if Empty: Write a code to check is list empty.
Expected Output:
Initial list: [10, 20, 30, 40, 50]
Third item: 30
Length of the list: 5
list is not empty
+ Hint
- Remember that list indices start from 0. So, the third element will be at index 2. Use indexing to get a specific element.
- Use the
len()
function to get the number of elements. - An empty list has a length of 0.
+ Show Solution
Exercise 2: Perform List Manipulation
Given:
my_list = [10, 20, 30, 40, 50]
Code language: Python (python)
Perform following list manipulation operations on given list
- Change Element: Change the second element of a list to 200 and print the updated list.
- Append Element: Add 600 o the end of a list and print the new list.
- Insert Element: Insert 300 at the third position (index 2) of a list and print the result.
- Remove Element (by value): Remove 600 from the list and print the list.
- Remove Element (by index): Remove the element at index 0 from the list print the list.
Expected Output:
Initial list: [10, 20, 30, 40, 50]
After changing second element: [10, 200, 30, 40, 50]
List after appending 600: [10, 200, 30, 40, 50, 600]
List after inserting 300 at index 2: [10, 200, 300, 30, 40, 50, 600]
List after removing 600 (by value): [10, 200, 300, 30, 40, 50]
List after removing element at index 0: [200, 300, 30, 40, 50]
+ Hint
- You can modify an element by assigning a new value to its index.
- Use the
append()
method to add an item to the end. - Use the
insert()
method to add an item at a specific position. - Use the
remove()
method to delete an item by its value. - Use the
pop()
method ordel
statement to delete an item by its index.
+ Show Solution
Exercise 3: Sum and average of all numbers in a list
Calculate and print the sum and average of all numbers in a list.
Given:
my_list = [10, 20, 30, 40, 50]
Code language: Python (python)
Expected Output:
Sum: 150
Average: 30.0
+ Hint
Python has built-in functions sum()
to easily calculate the sum of numbers in a list and to determine the number of elements (length) in a list.
+ Show Solution
Explanation:
sum(numbers)
is a built-in function that directly calculates the sum of all numeric elements in the list.len(numbers)
is another built-in function that returns the number of elements in the list.- We then calculate
average
by dividingtotal_sum
bylen(numbers)
.
Exercise 4: Reverse a list
Given:
list1 = [100, 200, 300, 400, 500]
Code language: Python (python)
Expected output:
[500, 400, 300, 200, 100]
Show Hint
Use the list function reverse()
Show Solution
Solution 1: list function reverse()
Solution 2: Using negative slicing
-1 indicates to start from the last item.
Exercise 5: Turn every item of a list into its square
Given a list of numbers. write a program to turn every item of a list into its square.
Given:
numbers = [1, 2, 3, 4, 5, 6, 7]
Code language: Python (python)
Expected output:
[1, 4, 9, 16, 25, 36, 49]
Show Hint
Iterate numbers from a list one by one using a for loop and calculate the square of the current number
Show Solution
Solution 1: Using loop and list method
- Create an empty result list
- Iterate a numbers list using a loop
- In each iteration, calculate the square of a current number and add it to the result list using the
append()
method.
Solution 2: Use list comprehension
Exercise 6: Find Maximum and Minimum
Find and print the largest and smallest number in a list [8, 2, 15, 1, 9]
.
Given:
data = [8, 2, 15, 1, 9]
Code language: Python (python)
Expected Output:
Largest number: 15
Smallest number: 1
+ Hint
Python provides built-in functions max()
and min()
for finding the maximum and minimum values in a list.
+ Show Solution
Exercise 7: Count Occurrences
Count and print how many times 'Football'
appears in list.
Given:
sports = ['Cricket', 'Football', 'Hockey', 'Football', 'Tennis'].
Code language: Python (python)
+ Hint
Python lists have a count()
method that allows you to count the occurrences of a specific element within the list.
+ Show Solution
Exercise 8: Sort a list of numbers
Sort a given list of numbers in ascending order and print it.
Given: numbers = [5, 2, 8, 1, 9]
Expected Output:
Original list: [5, 2, 8, 1, 9]
Sorted list: [1, 2, 5, 8, 9]
+ Hint
Python lists have a built-in method sort()
to sort elements in-place, and there’s also a built-in function sorted()
that returns a new sorted list without modifying the original.
+ Show Solution
Exercise 9: Create a copy of a list
Create a copy of a list [10, 20, 30]
and modify the copy. Print both the original and the copied list to demonstrate they are independent.
+ Hint
Simple assignment (new_list = original_list
) does not create a true copy; it just creates another reference to the same list. For a “shallow copy, you need to use method such as slicing, list()
constructor, or the copy()
method.
+ Show Solution
Explanation:
- List slicing (
[:]
) is used to create a shallow copy. It effectively creates a new list containing all the elements of the original, socopied_list
is a distinct object in memory fromoriginal_list
. another_copy = list(original_list)
: This uses thelist()
constructor to create a new list from an existing one, also resulting in a shallow copy.third_copy = original_list.copy()
: This is the most explicit way to create a shallow copy, available from Python 3.3 onwards.
Exercise 10: Combine two lists
Combine given two lists into a single list and print it.
Given:
list_a = [1, 2]
list_b = [3, 4]
Code language: Python (python)
Expected Output:
[1, 2, 3, 4]
+ Hint
You can combine lists using the +
operator, or by using the extend()
method, or by unpacking them into a new list.
+ Show Solution
Exercise 11: Remove empty strings from the list of strings
list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"]
Code language: Python (python)
Expected output:
["Mike", "Emma", "Kelly", "Brad"]
Show Hint
Use a filter()
function to remove the None
/ empty type from the list
Show Solution
Use a filter()
function to remove None
type from the list
Exercise 12: Remove Duplicates from list
Write a function that takes a list with duplicate elements and returns a new list with only unique elements.
Given: list_with_duplicates = [1, 2, 2, 3, 1, 4, 5, 4]
Expected Output:
[1, 2, 3, 4, 5]
+ Hint
Sets in Python inherently store only unique elements. You can convert a list to a set to get unique elements, and then convert it back to a list.
+ Show Solution
Exercise 13: Remove all occurrences of a specific item from a list
Given a Python list, write a program to remove all occurrences of item 20.
Given:
list1 = [5, 20, 15, 20, 25, 50, 20]
Code language: Python (python)
Expected output:
[5, 15, 25, 50]
Show Solution
Solution 1: Use the list comprehension
Solution 2: while loop (slow solution)
Exercise 14: List Comprehension for Numbers
Use list comprehension to create a new list containing only the numbers from a given list.
Given:
my_list = [1, 2, 3, 'Jessa', 4, 5, 'Kelly', 'Jhon', 6]
Code language: Python (python)
Expected Output:
[1, 2, 3, 4, 5, 6]
+ Hint
List comprehensions provide a concise way to create lists. You need to combine an iteration with a conditional check using isinstance()
method to filter elements based on their type.
+ Show Solution
Note: if isinstance(item, (int, float))
: This is the filtering condition. isinstance()
is a built-in function that checks if an object is an instance of a particular class or a tuple of classes
Exercise 15: Access Nested Lists
Given a nested list, print the element '55'
.
Given:
nested_list = <span style="background-color: initial; font-family: inherit; font-size: inherit; text-align: initial; color: initial;">[[10, 20, 30], [44, 55, 66], [77, 87, 99]]</span>
Code language: Python (python)
+ Hint
To access elements in a nested list, you need to use multiple sets of square brackets, one for each level of nesting, specifying the index at each level.
+ Show Solution
Exercise 16: Flatten Nested List
Write a function to flatten a list of lists into a single, non-nested list. (e.g., [[1, 2], [3, 4]]
becomes [1, 2, 3, 4]
).
Given:
list_of_lists = [[1, 2], [3, 4], [5, 6, 7]]
Code language: Python (python)
Expected Output:
[1, 2, 3, 4, 5, 6, 7]
+ Hint
Iterate through the outer list, and for each sublist, iterate through its elements and append them to a new flattened list. You can also use list comprehension to make code concise.
+ Show Solution
Solution 1: Without list comprehension
Solution 2: list comprehension
Exercise 17: Concatenate two lists index-wise
Write a program to add two lists index-wise. Create a new list that contains the 0th index item from both the list, then the 1st index item, and so on till the last element. any leftover items will get added at the end of the new list.
Given:
list1 = ["M", "na", "i", "Ke"]
list2 = ["y", "me", "s", "lly"]
Code language: Python (python)
Expected output:
['My', 'name', 'is', 'Kelly']
Show Hint
Use list comprehension with the zip()
function
Show Solution
Use the zip()
function. This function takes two or more iterables (like list, dict, string), aggregates them in a tuple, and returns it.
Exercise 18: Concatenate two lists in the following order
list1 = ["Hello ", "take "]
list2 = ["Dear", "Sir"]
Code language: Python (python)
Expected output:
['Hello Dear', 'Hello Sir', 'take Dear', 'take Sir']
Show Hint
Use a list comprehension to iterate two lists using a for loop and concatenate the current item of each list.
Show Solution
Exercise 19: Iterate both lists simultaneously
Given a two Python list. Write a program to iterate both lists simultaneously and display items from list1 in original order and items from list2 in reverse order.
Given
list1 = [10, 20, 30, 40]
list2 = [100, 200, 300, 400]
Code language: Python (python)
Expected output:
10 400 20 300 30 200 40 100
Show Solution
- The
zip()
function can take two or more lists, aggregate them in a tuple, and returns it. - Pass the first argument as a
list1
and seconds argument as alist2[::-1]
(reverse list using list slicing) - Iterate the result using a
for
loop
Exercise 21: Add new item to list after a specified item
Write a program to add item 7000 after 6000 in the following Python List
Given:
list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]
Code language: Python (python)
Expected output:
[10, 20, [300, 400, [5000, 6000, 7000], 500], 30, 40]
Show Hint
The given list is a nested list. Use indexing to locate the specified item, then use the append()
method to add a new item after it.
Show Solution
Use the append()
method
Exercise 22: Extend nested list by adding the sublist
You have given a nested list. Write a program to extend it by adding the sublist ["h", "i", "j"]
in such a way that it will look like the following list.
Given List:
list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]
# sub list to add
sub_list = ["h", "i", "j"]
Code language: Python (python)
Expected Output:
['a', 'b', ['c', ['d', 'e', ['f', 'g', 'h', 'i', 'j'], 'k'], 'l'], 'm', 'n']
Show Hint
The given list is a nested list. Use indexing to locate the specified sublist item, then use the extend()
method to add new items after it.
Show Solution
Exercise 23: Replace list’s item with new value if found
You have given a Python list. Write a program to find value 20 in the list, and if it is present, replace it with 200. Only update the first occurrence of an item.
Given:
list1 = [5, 10, 15, 20, 25, 50, 20]
Code language: Python (python)
Expected output:
[5, 10, 15, 200, 25, 50, 20]
Show Hint
- Use list method
index(20)
to get the index number of a 20 - Next, update the item present at the location using the index number