PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
  • Quizzes
  • Code Editor
Home » Python Exercises » Python List Exercise with Solutions

Python List Exercise with Solutions

Updated on: May 23, 2025 | 207 Comments

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.

Also Read:

  • Python List
  • Python List Quiz
  • Python List Interview Questions

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

  1. Access Elements: Print the third element.
  2. List Length: Print the number of elements in the list
  3. 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
my_list = [10, 20, 30, 40, 50]
print("Initial list:", my_list)

# Print the third element.
print("Third item: ", my_list[2])

# list size
list_length = len(my_list)
print("Length of the list:", list_length)

# list empty
if list_length == 0:
  print("list is empty")
else:
  print("list is not empty")Code language: Python (python)

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

  1. Change Element: Change the second element of a list to 200 and print the updated list.
  2. Append Element: Add 600 o the end of a list and print the new list.
  3. Insert Element: Insert 300 at the third position (index 2) of a list and print the result.
  4. Remove Element (by value): Remove 600 from the list and print the list.
  5. 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
  1. You can modify an element by assigning a new value to its index.
  2. Use the append() method to add an item to the end.
  3. Use the insert() method to add an item at a specific position.
  4. Use the remove() method to delete an item by its value.
  5. Use the pop() method or del statement to delete an item by its index.
+ Show Solution
my_list = [10, 20, 30, 40, 50]
print("Initial list:", my_list)

# Change the second element (at index 1) to 200
my_list[1] = 200
print("After changing second element:", my_list)

# Add 600 to the end of the list
my_list.append(600)
print("List after appending 600:", my_list)

# Insert 300 at index 2
my_list.insert(2, 300)
print("List after inserting 300 at index 2:", my_list)

# Remove 600 from the list (by value)
my_list.remove(600)
print("List after removing 600 (by value):", my_list)

# Remove the element at index 0 (using del)
del my_list[0]
print("List after removing element at index 0:", my_list)Code language: Python (python)

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
numbers = [10, 20, 30, 40, 50]

# Calculate the sum
total_sum = sum(numbers)

# Calculate the average
# The average is the sum divided by the number of elements
average = total_sum / len(numbers)

# Print the results
print("Sum:", total_sum)
print("Average:", average)Code language: Python (python)

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 dividing total_sum by len(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()

list1 = [100, 200, 300, 400, 500]
list1.reverse()
print(list1)Code language: Python (python)

Solution 2: Using negative slicing

-1 indicates to start from the last item.

list1 = [100, 200, 300, 400, 500]
list1 = list1[::-1]
print(list1)Code language: Python (python)

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.
numbers = [1, 2, 3, 4, 5, 6, 7]
# result list
res = []
for i in numbers:
    # calculate square and add to the result list
    res.append(i * i)
print(res)Code language: Python (python)

Solution 2: Use list comprehension

numbers = [1, 2, 3, 4, 5, 6, 7]
res = [x * x for x in numbers]
print(res)Code language: Python (python)

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
# List of numbers
data = [8, 2, 15, 1, 9]

# Find the maximum number
maximum_number = max(data)

# Find the minimum number
minimum_number = min(data)

# Print the results
print("Largest number:", maximum_number)
print("Smallest number:", minimum_number)Code language: Python (python)

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
# List of fruits
sports = ['Cricket', 'Football', 'Hockey', 'Football', 'Tennis']

# Count occurrences of 'Football'
football_count = sports.count('Football')
print("Count:", football_count)Code language: Python (python)

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
numbers = [5, 2, 8, 1, 9]
print("Original list:", numbers)

# Method 1: Using the sort() method (sorts in-place)
numbers.sort()
print("Sorted list (in-place using .sort()):", numbers)

# Resetting for demonstration of sorted()
numbers = [5, 2, 8, 1, 9]
print("\nOriginal list for sorted() demonstration:", numbers)

# Method 2: Using the sorted() function (returns a new sorted list)
sorted_numbers = sorted(numbers)
print("New sorted list (using sorted()):", sorted_numbers)
print("Original list after sorted() (unchanged):", numbers)Code language: Python (python)

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
original_list = [10, 20, 30]
print("Original list initially:", original_list)

# Create a copy using slicing
# This is a common and concise way to create a shallow copy
copied_list = original_list[:]

# Modify the copied list
copied_list.append(40)
copied_list[0] = 100

print("Original list after modifying copy:", original_list)
print("Copied list after modification:", copied_list)

# Demonstration using list() constructor
another_copy = list(original_list)
another_copy.append(50)
print("\nOriginal list after another_copy modification:", original_list)
print("Another copied list:", another_copy)

# Demonstration using .copy() method (Python 3+)
third_copy = original_list.copy()
third_copy[0] = 999
print("\nOriginal list after third_copy modification:", original_list)
print("Third copied list:", third_copy)Code language: Python (python)

Explanation:

  • List slicing ([:]) is used to create a shallow copy. It effectively creates a new list containing all the elements of the original, so copied_list is a distinct object in memory from original_list.
  • another_copy = list(original_list): This uses the list() 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
list_a = [1, 2]
list_b = [3, 4]

# Method 1: Using the + operator (creates a new list)
combined_list_plus = list_a + list_b
print("Combined list (using + operator):", combined_list_plus)

# Method 2: Using the extend() method (modifies list_a in-place)
temp_list = [1, 2]
temp_list.extend(list_b)
print("Combined list (using .extend() on temp_list):", temp_list)

# Method 3: Using unpacking (creates a new list - Python 3.5+)
combined_list_unpacking = [*list_a, *list_b]
print("Combined list (using unpacking *):", combined_list_unpacking)Code language: Python (python)

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

list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"]

# remove None from list1 and convert result into list
res = list(filter(None, list1))
print(res)Code language: Python (python)

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
list_with_duplicates = [1, 2, 2, 3, 1, 4, 5, 4]

unique_elements_set = set(list_with_duplicates)
unique_list = list(unique_elements_set)
print(f"Original list: {list_with_duplicates}")
print(f"List with unique elements: {unique_list}")Code language: Python (python)

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

list1 = [5, 20, 15, 20, 25, 50, 20]

# list comprehension
# remove specific items and return a new list
def remove_value(sample_list, val):
    return [i for i in sample_list if i != val]

res = remove_value(list1, 20)
print(res)Code language: Python (python)

Solution 2: while loop (slow solution)

list1 = [5, 20, 15, 20, 25, 50, 20]

while 20 in list1:
    list1.remove(20)
print(list1)Code language: Python (python)

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
mixed_list = [1, 2, 3, 'Jessa', 4, 5, 'Kelly', 'Jhon', 6]
print(f"Original mixed list: {mixed_list}")

# Use list comprehension to filter for numbers (integers and floats)
# isinstance(item, (int, float)) checks if the item is an integer OR a float
numbers_only_list = [item for item in mixed_list if isinstance(item, (int, float))]

print(f"List containing only numbers: {numbers_only_list}")Code language: Python (python)

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
nested_list = [[10, 20, 30], [44, 55, 66], [77, 87, 99]]
print(f"Nested list: {nested_list}")

# To access 55:
# 1. The list [44, 55, 66] is at index 1 of the main nested_list.
# 2. Within [44, 55, 66], the element 55 is at index 1.
element_55 = nested_list[1][1]

print(f"The element '55' is: {element_55}")Code language: Python (python)

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

def flatten_list(nested_list):
 
  flattened = []
  for sublist in nested_list:
    for item in sublist:
      flattened.append(item)
  return flattened

# Alternative and often more Pythonic using list comprehension
def flatten_list_comprehension(nested_list):
  return [item for sublist in nested_list for item in sublist]

# Test cases
list_of_lists = [[1, 2], [3, 4], [5, 6, 7]]
print(f"Original nested list: {list_of_lists}")

flattened_result = flatten_list(list_of_lists)
print(f"Flattened list (using loops): {flattened_result}")

flattened_result_comp = flatten_list_comprehension(list_of_lists)
print(f"Flattened list (using list comprehension): {flattened_result_comp}")Code language: Python (python)

Solution 2: list comprehension

# Alternative and often more Pythonic using list comprehension
def flatten_list_comprehension(nested_list):
  return [item for sublist in nested_list for item in sublist]

# Test cases
list_of_lists = [[1, 2], [3, 4], [5, 6, 7]]
print(f"Original nested list: {list_of_lists}")

flattened_result_comp = flatten_list_comprehension(list_of_lists)
print(f"Flattened list (using list comprehension): {flattened_result_comp}")Code language: Python (python)

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.

list1 = ["M", "na", "i", "Ke"] 
list2 = ["y", "me", "s", "lly"]
list3 = [i + j for i, j in zip(list1, list2)]
print(list3)Code language: Python (python)

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
list1 = ["Hello ", "take "]
list2 = ["Dear", "Sir"]

res = [x + y for x in list1 for y in list2]
print(res)Code language: Python (python)

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 Hint

Use the zip() function. This function takes two or more iterables (like list, dict, string), aggregates them in a tuple, and returns it.

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 a list2[::-1] (reverse list using list slicing)
  • Iterate the result using a for loop
list1 = [10, 20, 30, 40]
list2 = [100, 200, 300, 400]

for x, y in zip(list1, list2[::-1]):
    print(x, y)Code language: Python (python)

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

list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]

# understand indexing
# list1[0] = 10
# list1[1] = 20
# list1[2] = [300, 400, [5000, 6000], 500]
# list1[2][2] = [5000, 6000]
# list1[2][2][1] = 6000

# solution
list1[2][2].append(7000)
print(list1)Code language: Python (python)

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
list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]
sub_list = ["h", "i", "j"]

# understand indexing
# list1[2] = ['c', ['d', 'e', ['f', 'g'], 'k'], 'l']
# list1[2][1] = ['d', 'e', ['f', 'g'], 'k']
# list1[2][1][2] = ['f', 'g']

# solution
list1[2][1][2].extend(sub_list)
print(list1)Code language: Python (python)

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
Show Solution
list1 = [5, 10, 15, 20, 25, 50, 20]

# get the first occurrence index
index = list1.index(20)

# update item present at location
list1[index] = 200
print(list1)Code language: Python (python)

Filed Under: Python, Python Basics, Python Exercises

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Image

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Loading comments... Please wait.

In: Python Python Basics Python Exercises
TweetF  sharein  shareP  Pin

  Python Exercises

  • All Python Exercises
  • Basic Exercise for Beginners
  • Input and Output Exercise
  • Loop Exercise
  • Functions Exercise
  • String Exercise
  • Data Structure Exercise
  • List Exercise
  • Dictionary Exercise
  • Set Exercise
  • Tuple Exercise
  • Date and Time Exercise
  • OOP Exercise
  • File Handling Exercise
  • Python JSON Exercise
  • Random Data Generation Exercise
  • NumPy Exercise
  • Pandas Exercise
  • Matplotlib Exercise
  • Python Database Exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2025 pynative.com

Advertisement