PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python Exercises » Python list Exercises: 45 Coding Problems with Solutions

Python list Exercises: 45 Coding Problems with Solutions

Updated on: April 14, 2026 | 210 Comments

This article provides 45 Python list practice questions with solutions.

These exercises cover fundamental list CRUD operations, slicing, and sorting. They also include intermediate logic like filtering, comprehensions, and nested list manipulation. Additionally, they explore advanced algorithmic challenges such as flattening, rotating, statistical analysis, and restructuring lists into complex data structures like dictionaries.

Each coding challenge includes a Practice Problem, Hint, Solution code, and detailed Explanation, ensuring you don’t just copy code, but genuinely practice and understand how and why it works.

  • All solutions have been fully tested on Python 3.
  • Interactive Learning: Use our Online Code Editor to solve these exercises in real time.

Also See:

  • Python List: Read a guide on Python list to solve this exercise.
  • Python List Quiz: MCQs to help you get familiar with Python list.
  • Python List Interview Questions

If you have other solutions, please share them in the comments to help fellow developers.

+ Table of Contents (45 Exercises)

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. Find Maximum and Minimum from List
  • Exercise 5. Calculate the Product of All Elements
  • Exercise 6. Count Even and Odd Numbers
  • Exercise 7. Reverse a List
  • Exercise 8. Sort a List of Numbers
  • Exercise 9. Create a Copy of a List
  • Exercise 10. Combine Two Lists
  • Exercise 11. List Slicing: Extract Middle Elements
  • Exercise 12. Swap Two Elements at Given Indices
  • Exercise 13. Access Nested Lists (Simple Indexing)
  • Exercise 14. Check if List Contains a Specific Item
  • Exercise 15. Find the Longest String in a List
  • Exercise 16. Turn Every Item of a List into its Square (List Comprehension)
  • Exercise 17. Count Occurrences of an Item
  • Exercise 18. Remove All Occurrences of a Specific Item
  • Exercise 19. Remove Empty Strings from a List of Strings
  • Exercise 20. Remove Duplicates from List
  • Exercise 21. List Comprehension for Filtering Numbers
  • Exercise 22. Concatenate Two Lists Index-wise
  • Exercise 23. Iterate Both Lists Simultaneously
  • Exercise 24. Add New Item After a Specified Item
  • Exercise 25. Replace List’s Item with New Value if Found
  • Exercise 26. Find the Second Largest Number in a List
  • Exercise 27. Find the Most Frequent Element
  • Exercise 28. Extract Every Nth Element from a List
  • Exercise 29. Check if List is Palindrome
  • Exercise 30. Find All Common Elements Between Three Lists
  • Exercise 31. Filter Strings by Length in a List
  • Exercise 32. Check if List is Sorted
  • Exercise 33. List to Dictionary Conversion
  • Exercise 34. Find the Difference Between Two Lists
  • Exercise 35. Remove Negative Numbers In-place
  • Exercise 36. Extend Nested List by Adding a Sublist
  • Exercise 37. Concatenate Two Lists in a Specific Order
  • Exercise 38. Flatten Nested List (2D to 1D)
  • Exercise 39. Flatten a Deeply Nested List (Recursion)
  • Exercise 40. Calculate Cumulative Sum (Prefix Sums)
  • Exercise 41. Rotate a List (Left or Right by k positions)
  • Exercise 42. Split List into Chunks of Size N
  • Exercise 43. Move All Zeros to the End (Maintaining Order)
  • Exercise 44. Generate Prime Numbers using List Comprehension
  • Exercise 45. Find All Subsets of a List (Power Set)

Exercise 1. Perform Basic List Operations

Practice Problem: Write a script to perform the following three operations on given list

  1. Access the third element of a list
  2. List Length: Print the total number of items
  3. Check if the list is empty

Exercise Purpose: Before mastering complex algorithms, you must master data access: indexing, sizing, and validation. Quickly checking if a list has data prevents “Index Out of Range” errors that crash programs.

Given Input: numbers = [10, 20, 30, 40, 50]

Expected Output:

Third element: 30
Length of list: 5
Is the list empty? False
Hint
  • Remember that Python uses zero-based indexing, so the third element is actually at index 2.
  • To check if a list is empty, you can check if len(list) == 0 or simply use the list’s boolean value.
Solution
sample_list = [10, 20, 30, 40, 50]

# a) Access Elements
print(f"Third element: {sample_list[2]}")

# b) List Length
print(f"Length of list: {len(sample_list)}")

# c) Check if Empty
is_empty = len(sample_list) == 0
print(f"Is the list empty? {is_empty}")Code language: Python (python)

Explanation to Solution:

  • sample_list[2]: Since Python starts counting at 0, index 2 points to the third item (10 ->0, 20 -> 1, 30 -> 2).
  • len(): This is a built-in function that returns the count of items in an object. It runs in O(1) time because Python tracks the list size in the background.
  • len(sample_list) == 0: This evaluates to a Boolean (True/False). In Python, an empty list [] is also considered “Falsy,” meaning if not sample_list: is another common way to check for emptiness.

Exercise 2. Perform List Manipulation

Practice Problem: Take a given list and modify it through five specific actions:

  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.

Exercise Purpose: Python lists are mutable, meaning they can be changed after they are created. This exercise demonstrates the various ways to “reshape” your data dynamically during execution.

Given Input: Initial List: [100, 50, 400, 500]

Expected Output:

Updated (Change): [100, 200, 400, 500]
Updated (Append): [100, 200, 400, 500, 600]
Updated (Insert): [100, 200, 300, 400, 500, 600]
Updated (Remove 600): [100, 200, 300, 400, 500]
Updated (Remove Index 0): [200, 300, 400, 500]
Hint
  • Use list[index] = value for updates,
  • .append() for the end,
  • .insert(index, value) for specific spots,
  • and .remove() or .pop() for deletions.
Solution
list_m = [100, 50, 400, 500]

# a) Change Element
list_m[1] = 200
print(f"Updated (Change): {list_m}")

# b) Append Element
list_m.append(600)
print(f"Updated (Append): {list_m}")

# c) Insert Element
list_m.insert(2, 300)
print(f"Updated (Insert): {list_m}")

# d) Remove Element by value
list_m.remove(600)
print(f"Updated (Remove 600): {list_m}")

# e) Remove Element by index
list_m.pop(0)
print(f"Updated (Remove Index 0): {list_m}")Code language: Python (python)

Explanation to Solution:

  • insert(2, 300): This shifts all elements from index 2 onwards to the right to make room for the new value.
  • .remove(600): This searches for the value 600 and deletes the first occurrence. If 600 wasn’t in the list, this would raise a ValueError.
  • .pop(0): Unlike remove, pop works on the “address” (index). It also returns the value it removed, which is handy if you need to use that data elsewhere.

Exercise 3. Sum and Average of All Numbers in a List

Practice Problem: Calculate the total sum of all integers in a list and find the arithmetic mean (average).

Exercise Purpose: Aggregation is the heart of data science. This exercise teaches you how to reduce a collection of multiple data points into a single, meaningful summary statistic.

Given Input: Numbers: [10, 20, 30, 40, 50]

Expected Output:

Sum: 150
Average: 30.0
Hint

Python has a built-in sum() function. To get the average, divide that sum by the number of elements in the list.

Solution
nums = [10, 20, 30, 40, 50]

total_sum = sum(nums)
average = total_sum / len(nums)

print(f"Sum: {total_sum}")
print(f"Average: {average}")Code language: Python (python)

Explanation to Solution:

  • sum(nums): This iterates through the list and adds each element to a running total. It’s much cleaner and faster than writing a manual for loop.
  • total_sum / len(nums): This applies the mathematical formula for a mean.

Exercise 4. Find Maximum and Minimum from List

Practice Problem: Identify the largest and smallest numerical values within a provided list.

Exercise Purpose: Finding extremes is vital for tasks like identifying the “best” price, the “highest” score, or detecting “outlier” data points in a dataset.

Given Input: Data: [45, 12, 89, 2, 67]

Expected Output:

Maximum: 89
Minimum: 2
Hint

Don’t reinvent the wheel! Python provides two highly optimized built-in functions specifically for this purpose.

Solution
data_points = [45, 12, 89, 2, 67]

max_val = max(data_points)
min_val = min(data_points)

print(f"Maximum: {max_val}")
print(f"Minimum: {min_val}")Code language: Python (python)

Explanation to Solution:

  • max() and min(): These functions iterate through the list once (O(n) time complexity) and keep track of the highest or lowest value seen so far.
  • Versatility: These functions aren’t just for numbers; they can also find the “maximum” string based on alphabetical order.

Exercise 5. Calculate the Product of All Elements

Practice Problem: Multiply every number in a list together to find the total product.

Exercise Purpose: While sum is built-in, “product” often requires you to think about how to accumulate values. This exercise reinforces the concept of an “accumulator variable” in a loop.

Given Input: Factors: [2, 3, 5, 7]

Expected Output: Product: 210

Hint
  • Start with a variable set to 1 (not 0, or your result will always be 0!).
  • Loop through the list and multiply your variable by each element.
Solution
factors = [2, 3, 5, 7]
product = 1

for x in factors:
    product *= x

print(f"Product: {product}")Code language: Python (python)

Explanation to Solution:

  • product = 1: In multiplication, 1 is the “identity element.” Starting at 1 ensures the first multiplication (1*2) correctly initiates the calculation.
  • product *= x: This is shorthand for product = product * x. Each iteration “rolls” the previous result into the next multiplication.
  • Alternative: If you are using Python 3.8+, you could also use math.prod(factors).

Exercise 6. Count Even and Odd Numbers

Practice Problem: Given a list of integers, iterate through the items and count how many are even and how many are odd.

Exercise Purpose: This introduces Flow Control and the Modulo Operator. It is a classic “Filtering” pattern where you categorize data based on a mathematical property. In real-world apps, this is the foundation for things like alternating row colors in a table or batching jobs into two different queues.

Given Input: Numbers: [10, 21, 4, 45, 66, 93, 11]

Expected Output:

Even numbers: 3
Odd numbers: 4
Hint

A number is even if it is divisible by 2 with no remainder. In Python, use the % operator: if num % 2 == 0:.

Solution
numbers = [10, 21, 4, 45, 66, 93, 11]
even_count = 0
odd_count = 0

for num in numbers:
    if num % 2 == 0:
        even_count += 1
    else:
        odd_count += 1

print(f"Even numbers: {even_count}")
print(f"Odd numbers: {odd_count}")Code language: Python (python)

Explanation to Solution:

  • num % 2 == 0: This checks the remainder of num/2. If the remainder is 0, the logic path for “Even” executes.
  • Counters: We initialize even_count and odd_count at zero. This is a common pattern called the Accumulator Pattern, where we increment a variable based on specific criteria found during iteration.

Exercise 7. Reverse a List

Practice Problem: Take a list and reverse the order of its elements.

Exercise Purpose: Reversal is a fundamental operation in data structures (like reversing a string or a linked list). Python provides multiple ways to do this, and understanding the difference between In-place Reversal (changing the original) and Slicing (creating a new one) is crucial for memory management.

Given Input: List: [100, 200, 300, 400, 500]

Expected Output: Reversed List: [500, 400, 300, 200, 100]

Hint
  • You can use the built-in .reverse() method for an in-place change,
  • Or the slice syntax [::-1] to create a reversed copy.
Solution
list1 = [100, 200, 300, 400, 500]

# Method 1: Slicing (creates a new list)
reversed_list = list1[::-1]

print(f"Reversed List: {reversed_list}")Code language: Python (python)

Explanation to Solution:

  • [::-1]: This is “Pythonic” shorthand for slicing. It tells Python to start at the end, stop at the beginning, and move with a “step” of -1.
  • Efficiency: Slicing is very fast because it’s implemented in highly optimized C code under the hood, though it does create a new object in memory.

Exercise 8. Sort a List of Numbers

Practice Problem: Sort a list of numbers in ascending order (lowest to highest).

Exercise Purpose: Sorting is perhaps the most studied topic in Computer Science. It turns chaotic data into organized data, which is a prerequisite for high-speed search algorithms like Binary Search. Python uses Timsort, an efficient, hybrid sorting algorithm.

Given Input: Unsorted: [56, 12, 89, 3, 22]

Expected Output: Sorted List: [3, 12, 22, 56, 89]

Hint

Use the .sort() method to modify the list directly, or the sorted() function if you want to keep the original list untouched.

Solution
data = [56, 12, 89, 3, 22]
data.sort()

print(f"Sorted List: {data}")Code language: Python (python)

Explanation to Solution:

  • .sort(): This performs an “in-place” sort. It doesn’t return anything; it simply rearranges the elements at their current memory addresses.
  • Complexity: Python’s sorting is O(n log n), which is the gold standard for comparison-based sorting efficiency.

Exercise 9. Create a Copy of a List

Practice Problem: Create a copy of an existing list so that modifying the copy does not change the original.

Exercise Purpose: This exercise addresses one of the most common “gotchas” for new Python programmers: Pass-by-Object-Reference. If you simply write list_b = list_a, both variables point to the same list in memory. Learning to “Clone” or “Copy” is vital for data integrity.

Given Input: Original: ["Apple", "Banana", "Cherry"]

Expected Output:

Original: ['Apple', 'Banana', 'Cherry']
Copy: ['Apple', 'Banana', 'Cherry']
(Verification: Modifying copy doesn't hurt original!)
Hint

Use the .copy() method or the list() constructor to create a shallow copy.

Solution
original = ["Apple", "Banana", "Cherry"]

# Create a true copy
new_copy = original.copy()

# Prove they are independent
new_copy.append("Date")

print(f"Original: {original}")
print(f"Copy: {new_copy}")Code language: Python (python)

Explanation to Solution:

  • By using .copy(), we allocate a new block of memory for new_copy. When we add “Date” to it, the original remains unaffected.
  • Shallow Copy: Note that .copy() creates a “shallow” copy. If the list contained other lists inside it, those nested lists would still be shared. For “deep” independence, you’d use the copy module’s deepcopy() function.

Exercise 10. Combine Two Lists

Practice Problem: Merge two separate lists into a single, unified list.

Exercise Purpose: Data often arrives in fragments from different sources (e.g., two different database queries). Combining or “Concatenating” them is the first step in data aggregation.

Given Input:

  • List A: ["Physics", "Chemistry"]
  • List B: ["Maths", "Biology"]

Expected Output: Combined List: ['Physics', 'Chemistry', 'Maths', 'Biology']

Hint

You can use the + operator to join them, or the .extend() method to add the second list into the first.

Solution
list_a = ["Physics", "Chemistry"]
list_b = ["Maths", "Biology"]

# Combine using the + operator
combined = list_a + list_b

print(f"Combined List: {combined}")Code language: Python (python)

Explanation to Solution:

  • Operator Overloading: In Python, the + operator is “overloaded” for lists. Instead of adding numbers, it knows to stitch the two sequences together.
  • New Object: Using + creates a third list, leaving the original two unchanged. If you wanted to save memory and didn’t need the original list_a, you would use list_a.extend(list_b) instead.

Exercise 11. List Slicing: Extract Middle Elements

Practice Problem: Given a list, extract a “slice” containing the middle three elements.

Exercise Purpose: Slicing is one of Python’s most powerful features. Unlike many languages that require manual loops to copy array sub-sections, Python uses [start:stop] syntax. This forms the foundation for data windowing and pagination in web development.

Given Input: List: [10, 20, 30, 40, 50, 60, 70]

Expected Output: Middle Three: [30, 40, 50]

Hint
  • The stop index in a slice is exclusive.
  • To get elements at indices 2, 3, and 4, your slice needs to go from 2 to 5.
Solution
sample_list = [10, 20, 30, 40, 50, 60, 70]

# Extracting from index 2 up to (but not including) index 5
middle_three = sample_list[2:5]

print(f"Middle Three: {middle_three}")Code language: Python (python)

Explanation to Solution:

  • sample_list[2:5]: This grabs items at index 2, index 3, and index 4.
    Exclusive Bound: Python stops before the second number. A good trick to remember: stop - start equals the number of items you get (5 – 2 = 3 items).

Exercise 12. Swap Two Elements at Given Indices

Practice Problem: Write a script to swap the positions of two elements in a list based on their indices.

Exercise Purpose: Swapping is the heart of every sorting algorithm like Bubble Sort or Quick Sort. While other languages require a temporary variable to hold a value during the swap, Python offers an elegant, one-line tuple unpacking method that is faster to write and less error-prone.

Given Input:

  • List: [23, 65, 19, 90]
  • Indices to Swap: 0 and 2

Expected Output:

Original: [23, 65, 19, 90]
Swapped: [19, 65, 23, 90]
Hint

Use the syntax list[a], list[b] = list[b], list[a] to perform the swap in a single step.

Solution
list_data = [23, 65, 19, 90]
idx1, idx2 = 0, 2

print(f"Original: {list_data}")

# Pythonic swap
list_data[idx1], list_data[idx2] = list_data[idx2], list_data[idx1]

print(f"Swapped: {list_data}")Code language: Python (python)

Explanation to Solution:

  • Tuple Unpacking: Python evaluates the right side first, creating a temporary tuple (list_data[2], list_data[0]) in memory, and then “unpacks” those values back into the positions on the left side.
  • No Temp Variable: This eliminates the need for a temp = a; a = b; b = temp logic, reducing the chance of accidental data loss.

Exercise 13. Access Nested Lists (Simple Indexing)

Practice Problem: Given a “list of lists,” access a specific item hidden inside the inner list.

Exercise Purpose: This exercise teaches you to navigate Multi-dimensional Data. Think of nested lists like a spreadsheet (Rows and Columns) or a theater seating chart. To find a specific seat, you need the row and seat numbers.

Given Input:

  • Nested List: [[1, 2], [3, 4, 5], [6, 7]]
  • Goal: Access the number 5.

Expected Output: Accessed Value: 5

Hint

Use double brackets. The first bracket [i] selects the inner list, and the second bracket [j] selects the item inside that list.

Solution
nested = [[1, 2], [3, 4, 5], [6, 7]]

# 5 is in the second sub-list (index 1)
# Inside that list, 5 is at index 2
value = nested[1][2]

print(f"Accessed Value: {value}")Code language: Python (python)

Explanation to Solution:

  • nested[1]: This retrieves the entire list [3, 4, 5].
  • [2]: We then look at index 2 of that specific sub-list to get the 5.
  • Complexity: This remains O(1) (constant time) because we are jumping directly to a memory address, no matter how large the lists are.

Exercise 14. Check if List Contains a Specific Item

Practice Problem: Write a check to see if a certain value exists within a list and print a message based on the result.

Exercise Purpose: This is a Membership Test. It’s the logic used for “Is this username taken?” or “Is this item in the shopping cart?” Python’s in operator makes this incredibly readable, almost like plain English.

Given Input:

  • Inventory: ["Laptop", "Mouse", "Monitor", "Keyboard"]
  • Target: "Tablet"

Expected Output: Is Tablet in inventory? False

Hint

Use an if statement with the in keyword for a clean, Boolean result.

Solution
inventory = ["Laptop", "Mouse", "Monitor", "Keyboard"]
target = "Tablet"

if target in inventory:
    print(f"Is {target} in inventory? True")
else:
    print(f"Is {target} in inventory? False")Code language: Python (python)

Explanation to Solution:

  • in Operator: Behind the scenes, Python iterates through the list and compares each item to your target.
    Performance Note: For a list, this is O(n), meaning if the list has a million items, it might have to check all million. (If you need to do this millions of times, you’d eventually switch to a set for O(1) speed).

Exercise 15. Find the Longest String in a List

Practice Problem: In a list of strings, identify which string has the most characters.

Exercise Purpose: This combines Iteration with Comparison. It teaches you how to evaluate an attribute of an object (its length) rather than just its raw value. This is used in text processing, UI layout, and data cleaning.

Given Input: Words: ["PHP", "Exercises", "Backend", "Python"]

Expected Output: Longest word: Exercises

Hint

You can use a loop and a “tracking variable,” or use the max() function with a special key argument.

Solution
words = ["PHP", "Exercises", "Backend", "Python"]

# The elegant way: find the max based on length
longest = max(words, key=len)

print(f"Longest word: {longest}")Code language: Python (python)

Explanation to Solution:

  • key=len: This tells the max() function: “Don’t find the ‘largest’ word alphabetically; find the one where the len() result is the highest.”
  • Tie-breaking: If two words have the same maximum length, Python’s max() will return the one that appeared first in the list.

Exercise 16. Turn Every Item of a List into its Square (List Comprehension)

Practice Problem: Given a list of numbers, create a new list where each number is replaced by its square (n2) using a single line of code.

Exercise Purpose: This is your introduction to List Comprehensions. In Python, writing a full for loop to build a new list is often considered un-Pythonic. List comprehensions execute faster and are cleaner to read, providing a concise way to map a function across a collection.

Given Input: List: [1, 2, 3, 4, 5]

Expected Output: Squared List: [1, 4, 9, 16, 25]

Hint
  • The syntax for a list comprehension is [expression for item in list].
  • Your expression here should be x * x.
Solution
numbers = [1, 2, 3, 4, 5]

# The shorthand way to create a new list
squared_numbers = [x * x for x in numbers]

print(f"Squared List: {squared_numbers}")Code language: Python (python)

Explanation to Solution:

  • for x in numbers: This handles the iteration logic internally.
  • x * x: This is the operation applied to every item before it is added to the new list.
  • Memory Efficiency: While this creates a new list in memory, the syntax is optimized at the C-level, making it faster than a manual .append() loop.

Exercise 17. Count Occurrences of an Item

Practice Problem: Find out how many times a specific value appears in a list.

Exercise Purpose: This is a basic form of Frequency Analysis. It’s used in everything from counting word occurrences in a document to verifying how many times a specific error code appears in a server log.

Given Input:

  • List: [10, 20, 30, 10, 40, 10, 50]
  • Target: 10

Expected Output: The number 10 appears 3 times.

Hint

Python lists have a built-in method called .count() that does exactly this without needing a manual counter variable.

Solution
sample_list = [10, 20, 30, 10, 40, 10, 50]
target = 10

# Use the built-in count method
occurrence_count = sample_list.count(target)

print(f"The number {target} appears {occurrence_count} times.")Code language: Python (python)

Explanation to Solution:

  • .count(): This method scans the list from start to finish ( O(n) complexity) and returns the total number of matches found.
  • Simplicity: By using built-in methods, you reduce the “surface area” for bugs (like accidentally resetting a counter variable).

Exercise 18. Remove All Occurrences of a Specific Item

Practice Problem: Delete every instance of a specific value from a list.

Exercise Purpose: This is a Filtering Operation. A common mistake is using .remove(), which deletes only the first occurrence. To remove all instances, you need to filter the list. This is essential for data scrubbing when you need to purge “bad data” or “flagged entries” entirely.

Given Input:

  • List: [5, 20, 15, 20, 25, 50, 20]
  • Item to remove: 20

Expected Output: Cleaned List: [5, 15, 25, 50]

Hint

Instead of trying to delete items from the current list (which can be messy), it is usually better to create a new list that only includes items that are not the target.

Solution
list_v = [5, 20, 15, 20, 25, 50, 20]
target = 20

# Filter the list using a comprehension
cleaned_list = [x for x in list_v if x != target]

print(f"Cleaned List: {cleaned_list}")Code language: Python (python)

Explanation to Solution:

  • if x != target: This condition acts as a “gatekeeper.” Only items that satisfy this condition are allowed into the new list.
  • Non-destructive: This method leaves the original list_v intact, which is a safer practice in larger software systems.

Exercise 19. Remove Empty Strings from a List of Strings

Practice Problem: Take a list of strings that contains empty entries ("") and remove them to keep only the valid text.

Exercise Purpose: Real-world data is often “noisy.” When you split a paragraph into words or import a CSV, you often end up with empty strings. Learning to “sanitize” your lists is a daily task for developers and data scientists.

Given Input: List: ["Mike", "", "Emma", "Kelly", "", "Brad"]

Expected Output: Cleaned Names: ['Mike', 'Emma', 'Kelly', 'Brad']

Hint
  • You can use the filter() function or a list comprehension.
  • In Python, an empty string "" evaluates to False, so you can just check the truthiness of the string.
Solution
names = ["Mike", "", "Emma", "Kelly", "", "Brad"]

# Method: Using filter with None
# filter(None, ...) removes all "Falsy" values (empty strings, 0, None)
cleaned_names = list(filter(None, names))

print(f"Cleaned Names: {cleaned_names}")Code language: Python (python)

Explanation to Solution:

  • filter(None, names): The filter function is highly efficient for large datasets. Passing None as the first argument tells Python to remove anything that is not “Truthy.”
  • list(): filter returns an “iterator” (to save memory). We wrap it in list() to convert it back into a standard list format.

Exercise 20. Remove Duplicates from List

Practice Problem: Remove all duplicate values from a list while keeping only one instance of each element.

Exercise Purpose: This exercise introduces Set Theory. In programming, you often need to ensure uniqueness (e.g., a list of unique email subscribers). While there are many ways to do this, using Python’s set or dict structures is the fastest way to handle the logic.

Given Input: List: [10, 20, 10, 30, 40, 40, 20, 50]

Expected Output: Unique List: [10, 20, 30, 40, 50]

Hint
  • A set cannot contain duplicates.
  • Converting a list to a set and back to a list is the quickest way to remove duplicates, though it might lose the original order. To keep the order, use dict.fromkeys().
Solution
duplicates = [10, 20, 10, 30, 40, 40, 20, 50]

# Method to remove duplicates while preserving order
unique_list = list(dict.fromkeys(duplicates))

print(f"Unique List: {unique_list}")Code language: Python (python)

Explanation to Solution:

  • dict.fromkeys(duplicates): Dictionary keys must be unique. When Python creates this dictionary, it keeps the first time it sees “10” and ignores all later “10”s.
  • Preserving Order: Unlike a standard set(), dict.fromkeys() preserves the order in which items first appeared (as of Python 3.7+).
  • Speed: This is an O(n) operation, making it significantly faster than using a loop to check if an item exists before adding it.

Exercise 21. List Comprehension for Filtering Numbers

Practice Problem: Given a list of integers, use list comprehension to create a new list that contains only the even numbers from the original list.

Exercise Purpose: This is the “Filter” part of the Map-Filter-Reduce paradigm. Here we focuses on Conditional Logic within a single line. It is the gold standard for creating subsets of data based on specific criteria.

Given Input: List: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Expected Output: Even Numbers: [2, 4, 6, 8, 10]

Hint

Add an if statement at the very end of your list comprehension: [item for item in list if condition].

Solution
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Extract only items that are divisible by 2
even_only = [x for x in numbers if x % 2 == 0]

print(f"Even Numbers: {even_only}")Code language: Python (python)

Explanation to Solution:

  • if x % 2 == 0: This condition acts as a “bouncer.” The variable x is only passed to the new list if it produces a remainder of 0 when divided by 2.
  • Readable Code: This replaces four lines of standard loop code with a single, highly readable statement that clearly defines what is being collected.

Exercise 22. Concatenate Two Lists Index-wise

Practice Problem: Given two lists of strings, combine them index-by-index to form a single list of concatenated strings.

Exercise Purpose: Data is often stored in parallel lists (e.g., First Names and Last Names). This exercise teaches you how to merge parallel data into a usable format, a common need for report generation and UI display.

Given Input:

  • List 1: ["Py", "is", "awes"]
  • List 2: ["thon", " ", "ome"]

Expected Output: Merged: ['Python', 'is ', 'awesome']

Hint

You can use a list comprehension combined with the zip() function to pair the elements before joining them.

Solution
list1 = ["Py", "is", "awes"]
list2 = ["thon", " ", "ome"]

# Zip them to pair (Py, thon), etc., then join with +
res = [i + j for i, j in zip(list1, list2)]

print(f"Merged: {res}")Code language: Python (python)

Explanation to Solution:

  • zip(list1, list2): This creates an iterator of tuples: ('Py', 'thon'), ('is', ' '), ('awes', 'ome').
  • i + j: Since these are strings, the + operator performs concatenation, gluing the two fragments together.

Exercise 23. Iterate Both Lists Simultaneously

Practice Problem: Use the zip() function to loop through two lists at once and print their values as pairs.

Exercise Purpose: Iterating through two lists with a single index variable is error-prone (you might hit an “Index Out of Range” if lists are different sizes). zip() is the Safe Parallel Iterator. It stops automatically at the end of the shortest list, preventing crashes.

Given Input:

  • List 1: [10, 20, 30]
  • List 2: [100, 200, 300]

Expected Output:

10 100
20 200
30 300
Hint

Use for item1, item2 in zip(list1, list2):.

Solution
list1 = [10, 20, 30]
list2 = [100, 200, 300]

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

Explanation to Solution:

  • Unpacking: The x, y syntax “unpacks” the tuple returned by zip at each step, making the variables immediately available without extra indexing.
  • Synchronization: This ensures that x and y always correspond to the same relative position in their respective sources.

Exercise 24. Add New Item After a Specified Item

Practice Problem: Find a specific item in a list and insert a new item immediately after it.

Exercise Purpose: Unlike append() (end) or insert() (fixed index), this is a Context-Aware Insertion. This is useful for things like adding a “New!” tag after a specific product name or inserting a middleware step into a list of processing functions.

Given Input:

  • List: [10, 20, 30, 40, 50]
  • Insert after: 30
  • New Item: 35

Expected Output: Updated List: [10, 20, 30, 35, 40, 50]

Hint
  • First, find the index of your target item using .index().
  • Then, use .insert() at index + 1.
Solution
list1 = [10, 20, 30, 40, 50]
target = 30
new_val = 35

# 1. Find where the target is
index = list1.index(target)

# 2. Insert at the position right after it
list1.insert(index + 1, new_val)

print(f"Updated List: {list1}")Code language: Python (python)

Explanation to Solution:

  • list1.index(30): Returns 2.
  • list1.insert(3, 35): Because we want it after 30, we target index 3.
  • Side Effect: Be aware that .index() only finds the first occurrence. If “30” appeared twice, this would only insert after the first one.

Exercise 25. Replace List’s Item with New Value if Found

Practice Problem: Find the first occurrence of a specific value in a list and replace it with a new value.

Exercise Purpose: This is a Selective Update. It mimics “Find and Replace” functionality. It teaches you how to identify a location in memory and overwrite it without affecting the rest of the list structure.

Given Input:

  • List: [5, 10, 15, 20, 25]
  • Find: 20
  • Replace with: 200

Expected Output: Modified List: [5, 10, 15, 200, 25]

Hint

Locate the index of the target value and then assign the new value directly to that index using list[index] = new_value.

Solution
list1 = [5, 10, 15, 20, 25]
target = 20
replacement = 200

# Locate and replace
if target in list1:
    index = list1.index(target)
    list1[index] = replacement

print(f"Modified List: {list1}")Code language: Python (python)

Explanation to Solution:

  • if target in list1: This is a crucial safety check. If you call .index() on a value that doesn’t exist, Python will throw a ValueError and crash your program.
  • In-place Modification: This directly changes list1 rather than creating a copy, making it highly efficient for memory usage.

Exercise 26. Find the Second Largest Number in a List

Practice Problem: Write a Python function that takes a list of numbers and returns the second largest value. Ensure the function handles lists with duplicate values correctly (e.g., if the list is [10, 10, 9], the second largest is 9).

Exercise Purpose: This exercise teaches you how to process data sets where “rank” matters. It also highlights the importance of handling duplicates. Simply sorting a list does not work if the largest number appears multiple times. It introduces the concept of using Sets to make data unique.

Given Input: List: [12, 35, 1, 10, 34, 1, 35]

Expected Output: Second Largest: 34

Hint
  • To ignore duplicates, convert the list into a set() first.
  • Then, you can either sort the unique values or remove the maximum value and find the new maximum.
Solution
def get_second_largest(nums):
    # Remove duplicates by converting to a set
    unique_nums = list(set(nums))
    
    if len(unique_nums) < 2:
        return None
    
    # Sort the list in descending order
    unique_nums.sort(reverse=True)
    
    # Return the second element
    return unique_nums[1]

# Test the function
numbers = [12, 35, 1, 10, 34, 1, 35]
result = get_second_largest(numbers)
print(f"List: {numbers}")
print(f"Second Largest: {result}")Code language: Python (python)

Explanation to Solution:

  • set(nums): This constructor removes all duplicate values. Without this, a list like [35, 35, 10] would incorrectly identify 35 as the second largest.
  • unique_nums.sort(reverse=True): By sorting in reverse, the largest values move to the front of the list.
  • unique_nums[1]: In a 0-indexed list, index 1 is the second position, representing the second largest value.

Exercise 27. Find the Most Frequent Element

Practice Problem: Create a script that identifies the “Mode” of a list—the element that appears most frequently. If there is a tie, returning one of the top elements is sufficient for this exercise.

Exercise Purpose: Finding the mode is a fundamental task in data science and statistics. This exercise introduces Frequency Mapping using dictionaries, a vital pattern for counting occurrences in any programming language.

Given Input: List: [1, 3, 3, 2, 1, 1, 4, 3, 3]

Expected Output: Mode: 3

Hint
  • Use a dictionary where the keys are the list items and the values are their counts.
  • Loop through the list to populate the dictionary, then find the key with the highest value.
Solution
def find_mode(arr):
    frequency = {}
    
    # Count occurrences of each element
    for item in arr:
        frequency[item] = frequency.get(item, 0) + 1
    
    # Find the key with the maximum value
    mode = max(frequency, key=frequency.get)
    return mode

# Test the function
data = [1, 3, 3, 2, 1, 1, 4, 3, 3]
result = find_mode(data)
print(f"List: {data}")
print(f"Mode: {result}")Code language: Python (python)

Explanation to Solution:

  • frequency.get(item, 0) + 1: This is a “safe” way to increment a count. If the item isn’t in the dictionary yet, it starts at 0 and adds 1.
  • max(frequency, key=frequency.get): This tells Python to look at the keys of the dictionary, but use the values (the counts) to determine which key is the “maximum.”

Exercise 28. Extract Every Nth Element from a List

Practice Problem: Write a function that accepts a list and an integer n, returning a new list containing every nth element from the original, starting from the first element (index 0).

Exercise Purpose: This exercise explores List Slicing, one of Python’s most powerful features. Understanding slicing notation allows you to manipulate sequences with minimal code, which is essential for tasks like data sampling.

Given Input:

  • List: ['a', 'b', 'c', 'd', 'e', 'f', 'g']
  • n: 3

Expected Output: Result: ['a', 'd', 'g']

Hint
  • Python’s slice syntax is list[start:stop:step].
  • You can achieve this result in a single line of code using the step parameter.
Solution
def extract_nth(lst, n):
    # Using list slicing with a step of n
    return lst[::n]

# Test the function
my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
n_value = 3
result = extract_nth(my_list, n_value)

print(f"Original: {my_list}")
print(f"Every {n_value}rd element: {result}")Code language: Python (python)

Explanation to Solution:

  • lst[::n]: The double colons tell Python to include the full range of the list (from start to end). The n at the end sets the “stride” or “step.”
  • Efficiency: Slicing is implemented in C at the interpreter level, making it significantly faster than writing a manual for loop to pick elements.

Exercise 29. Check if List is Palindrome

Practice Problem: Determine if a list reads the same forward and backward. The function should return True if it is a palindrome and False otherwise.

Exercise Purpose: Palindrome checks are classic logic tests. This exercise demonstrates how to compare a sequence against its own reverse, reinforcing concepts of Symmetry and sequence comparison.

Given Input: List: [1, 2, 3, 2, 1]

Expected Output: Is Palindrome: True

Hint
  • The easiest way to check this in Python is to compare the list to a reversed copy of itself.
  • You can reverse a list easily using slicing with a negative step: [::-1].
Solution
def is_palindrome(lst):
    # Compare the list to its reverse
    return lst == lst[::-1]

# Test cases
test1 = [1, 2, 3, 2, 1]
test2 = [1, 2, 3, 4, 5]

print(f"{test1} is palindrome? {is_palindrome(test1)}")
print(f"{test2} is palindrome? {is_palindrome(test2)}")Code language: Python (python)

Explanation to Solution:

  • lst[::-1]: This creates a new list that is a reversed version of the original.
  • ==: In Python, comparing two lists with == checks if they have the same length and if every corresponding element is identical.
  • Logic: If the original and the reverse are identical, the sequence is perfectly symmetrical.

Exercise 30. Find All Common Elements Between Three Lists

Practice Problem: Given three separate lists, write a function that returns a list containing only the elements that appear in all three.

Exercise Purpose: This exercise introduces Set Intersection. When you need to find commonalities across multiple data sources, converting them to sets and finding their intersection is the most efficient method (O(n) average time complexity).

Given Input:

  • List A: [1, 5, 10, 20]
  • List B: [6, 7, 20, 80, 100]
  • List C: [3, 4, 15, 20, 30, 70, 80]

Expected Output: Common Elements: [20]

Hint
  • Convert all lists into sets.
  • Use the & operator or the .intersection() method to find elements present in all of them.
Solution
def find_common(list1, list2, list3):
    # Convert lists to sets and find the intersection
    common = set(list1) & set(list2) & set(list3)
    
    # Convert back to list to match expected output format
    return list(common)

# Test the function
L1 = [1, 5, 10, 20]
L2 = [6, 7, 20, 80, 100]
L3 = [3, 4, 15, 20, 30, 70, 80]

result = find_common(L1, L2, L3)
print(f"Common elements: {result}")Code language: Python (python)

Explanation to Solution:

  • set(list1): Converts the list to a set to enable mathematical set operations.
  • &: The bitwise AND operator, when used with sets, performs an Intersection. It only keeps elements that exist in both sets.
  • Scalability: This approach is much faster than using nested loops, which would take O(n * m * p) time. Set intersection handles this in linear time relative to the total number of elements.

Exercise 31. Filter Strings by Length in a List

Practice Problem: Write a function that takes a list of strings and an integer k. The function should return a new list containing only the strings that have a length greater than or equal to k.

Exercise Purpose: This exercise introduces List Comprehensions, which are the “Pythonic” way to filter data. It demonstrates how to combine iteration and conditional logic into a single, readable line of code.

Given Input:

  • List: ["apple", "pie", "banana", "kiwi", "pear"]
  • k: 5

Expected Output: Filtered List: ['apple', 'banana']

Hint

Instead of using a traditional for loop with .append(), try the syntax: [item for item in list if condition].

Solution
def filter_by_length(strings, k):
    # Using list comprehension to filter strings
    return [s for s in strings if len(s) >= k]

# Test the function
words = ["apple", "pie", "banana", "kiwi", "pear"]
min_length = 5
result = filter_by_length(words, min_length)

print(f"Original: {words}")
print(f"Filtered (length >= {min_length}): {result}")Code language: Python (python)

Explanation to Solution:

  • for s in strings: This part iterates through every element in the input list.
  • if len(s) >= k: This is the filter condition. If a string is too short, it is simply skipped.
  • [s for ...]: This tells Python to take the current string s and place it into the new resulting list only if it passes the if check.

Exercise 32. Check if List is Sorted

Practice Problem: Create a function that determines if a list of numbers is sorted in non-decreasing (ascending) order. Return True if it is, and False otherwise.

Exercise Purpose: Checking order is a common prerequisite for algorithms like Binary Search. This exercise teaches you to perform Neighbor Comparison by examining an element and its immediate successor together.

Given Input: List: [10, 20, 30, 25, 40]

Expected Output: Is Sorted: False

Hint
  • A list is sorted if, for every index i, list[i] is less than or equal to list[i + 1].
  • You can use the all() function combined with a generator expression for a clean solution.
Solution
def is_list_sorted(lst):
    # Check if every element is <= the next element
    return all(lst[i] <= lst[i + 1] for i in range(len(lst) - 1))

# Test the function
nums1 = [10, 20, 30, 40]
nums2 = [10, 20, 30, 25, 40]

print(f"{nums1} sorted? {is_list_sorted(nums1)}")
print(f"{nums2} sorted? {is_list_sorted(nums2)}")Code language: Python (python)

Explanation to Solution:

  • range(len(lst) - 1): We stop one element before the end so that lst[i + 1] doesn’t go out of bounds.
  • lst[i] <= lst[i + 1]: This logic ensures each number is not larger than the one following it.
  • all(...): This function returns True only if every single comparison in the loop is True. If even one pair is out of order, it immediately returns False.

Exercise 33. List to Dictionary Conversion

Practice Problem: Given two lists of the same length, one containing keys and the other containing values. combine them into a single dictionary.

Exercise Purpose: In data processing, you often receive related data in separate arrays. This exercise teaches you how to use the zip() function to pair elements and transform them into a dictionary.

Given Input:

  • Keys: ["name", "age", "city"]
  • Values: ["Alice", 25, "New York"]

Expected Output:

Dictionary: {'name': 'Alice', 'age': 25, 'city': 'New York'}

Hint
  • The zip() function takes two iterables and “zips” them together into pairs.
  • You can pass these pairs directly into the dict() constructor.
Solution
def lists_to_dict(keys, values):
    # Zip pairs the elements, dict() converts pairs to key-value entries
    return dict(zip(keys, values))

# Test the function
fields = ["name", "age", "city"]
data = ["Alice", 25, "New York"]
result = lists_to_dict(fields, data)

print(f"Keys: {fields}")
print(f"Values: {data}")
print(f"Resulting Dict: {result}")Code language: Python (python)

Explanation to Solution:

  • zip(keys, values): This creates an iterator of tuples: ('name', 'Alice'), ('age', 25)....
  • dict(...): The dictionary constructor is smart enough to take a sequence of pairs and treat the first item as the key and the second as the value.
  • Constraint: If the lists are of different lengths, zip() will stop at the shortest list, effectively ignoring the extra elements in the longer list.

Exercise 34. Find the Difference Between Two Lists

Practice Problem: Write a function that finds the “difference” between two lists—specifically, all elements that are present in the first list but not in the second list.

Exercise Purpose: This exercise explores Set Logic and exclusion. It is a common task when synchronizing databases or filtering out “already processed” items from a new batch of data.

Given Input:

  • List A: [1, 2, 3, 4, 5]
  • List B: [2, 4, 6]

Expected Output: Difference (A – B): [1, 3, 5]

Hint

While you can use a loop, converting the second list to a set first makes the “search” much faster (O(1) lookup time instead of O(n)).

Solution
def get_difference(list_a, list_b):
    # Convert list_b to a set for high-performance lookups
    excluded = set(list_b)
    return [item for item in list_a if item not in excluded]

# Test the function
a = [1, 2, 3, 4, 5]
b = [2, 4, 6]
result = get_difference(a, b)

print(f"List A: {a}")
print(f"List B: {b}")
print(f"Elements in A but not B: {result}")Code language: Python (python)

Explanation to Solution:

  • set(list_b): By making list_b a set, Python can check if item not in excluded almost instantly, regardless of how large list_b is.
  • item not in excluded: This conditional keeps only the items that failed to find a match in the exclusion set.
  • Note: This preserves the original order of list_a, which a standard set subtraction (set(a) - set(b)) would not do.

Exercise 35. Remove Negative Numbers In-place

Practice Problem: Write a function that removes all negative numbers from a list without creating a new list. You must modify the original list object directly.

Exercise Purpose: This is a classic “trap” exercise. If you remove items while iterating forward, the indices shift and you will skip elements. This exercise teaches In-place Modification and the importance of iterating backwards or using slice assignment.

Given Input: List: [10, -5, 20, -1, 0, -8]

Expected Output: Modified List: [10, 20, 0]

Hint

To avoid the “shifting index” problem, iterate through the list in reverse (from the last index to the first). This way, removing an item doesn’t change the position of the elements you haven’t checked yet.

Solution
def remove_negatives_inplace(lst):
    # Iterate backwards through the indices
    for i in range(len(lst) - 1, -1, -1):
        if lst[i] < 0:
            del lst[i]

# Test the function
my_nums = [10, -5, 20, -1, 0, -8]
print(f"Before: {my_nums}")

remove_negatives_inplace(my_nums)
print(f"After (In-place): {my_nums}")Code language: Python (python)

Explanation to Solution:

  • range(len(lst) - 1, -1, -1): This creates a sequence of indices starting at the end and moving toward 0.
  • del lst[i]: This removes the element at the current index.
  • Why Reverse? If we deleted the element at index 1 while moving forward, the old index 2 would become the new index 1. The loop would then move to index 2, completely skipping the value that just shifted into index 1. Iterating backwards ensures that the indices of elements yet to be inspected remain stable.

Exercise 36. Extend Nested List by Adding a Sublist

Practice Problem: Write a function that iterates through a list of nested lists and appends a specific sublist (or value) to each inner list.

Exercise Purpose: Working with “lists of lists” is common in matrix manipulation and data grouping. This exercise reinforces the concept of Nested Iteration, accessing an object that exists inside another object and modifying it in place.

Given Input:

  • Nested List: [['apple', 'banana'], ['cherry', 'date']]
  • To Append: "elderberry"

Expected Output: Modified List: [['apple', 'banana', 'elderberry'], ['cherry', 'date', 'elderberry']]

Hint
  • Use a simple for loop to grab each sublist.
  • Once you have a reference to the sublist, use the .append() method to add the new value.
Solution
def extend_nested(nested_list, item):
    for sublist in nested_list:
        sublist.append(item)
    return nested_list

# Test the function
data = [['apple', 'banana'], ['cherry', 'date']]
extra = "elderberry"
result = extend_nested(data, extra)

print(f"Updated Nested List: {result}")Code language: Python (python)

Explanation to Solution:

  • for sublist in nested_list: This extracts each inner list one by one.
  • sublist.append(item): Because lists are mutable (changeable) objects in Python, appending to sublist modifies the original inner list inside data.
  • Memory Note: You aren’t creating a new list of lists here; you are reaching into the existing structure and adding a new “room” to each “house.”

Exercise 37. Concatenate Two Lists in a Specific Order

Practice Problem: Given two lists of strings, create a new list that contains every possible combination of elements from the first and second list, concatenated together.

Exercise Purpose: This exercise simulates a Cartesian Product. It is useful for generating permutations like combining first names with last names or product categories with sizes. It shows how Nested List Comprehensions can replace bulky nested loops.

Given Input:

  • List 1: ["Hello ", "Take "]
  • List 2: ["Dear", "Sir"]

Expected Output:

Result: ['Hello Dear', 'Hello Sir', 'Take Dear', 'Take Sir']

Hint
  • Use a list comprehension with two for clauses.
  • The first for iterates through List 1, and the second for iterates through List 2 for every item in the first.
Solution
def specific_concat(list1, list2):
    # Nested list comprehension for item-wise combination
    return [x + y for x in list1 for y in list2]

# Test the function
l1 = ["Hello ", "Take "]
l2 = ["Dear", "Sir"]
res = specific_concat(l1, l2)

print(f"List 1: {l1}")
print(f"List 2: {l2}")
print(f"Combined: {res}")Code language: Python (python)

Explanation to Solution:

  • for x in list1 for y in list2: This works like a nested loop. For the first item in list1 (“Hello “), it runs through all items in list2. Then it moves to the second item in list1 (“Take “) and repeats.
  • x + y: Since these are strings, the + operator performs concatenation.

Exercise 38. Flatten Nested List (2D to 1D)

Practice Problem: Take a 2D list (a list containing several lists) and “flatten” it into a single 1D list containing all the individual elements in their original order.

Exercise Purpose: Flattening is a core data-wrangling task. When you have data chunked into groups (like rows in a table) but need to perform a single operation on every individual piece, you must flatten the structure first.

Given Input: 2D List: [[1, 2, 3], [4, 5], [6, 7, 8, 9]]

Expected Output: 1D List: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Hint

You can use a nested list comprehension (similar to the previous exercise) or the extend() method within a loop.

Solution
def flatten_2d(nested):
    flat_list = []
    for sublist in nested:
        # extend adds all elements of the sublist to the end of flat_list
        flat_list.extend(sublist)
    return flat_list

# Test the function
matrix = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
result = flatten_2d(matrix)

print(f"Original 2D: {matrix}")
print(f"Flattened 1D: {result}")Code language: Python (python)

Explanation to Solution:

  • flat_list.extend(sublist): Unlike .append(), which would add the sublist itself as a single item, .extend() unpacks the sublist and adds each of its elements individually.
  • Order Preservation: This method ensures that the numbers stay in the sequence they appeared in the original nested structure.

Exercise 39. Flatten a Deeply Nested List (Recursion)

Practice Problem: Write a function that flattens a list of arbitrary depth. The list may contain integers or other lists, which in turn may contain even more lists (e.g., [1, [2, [3, 4]]]).

Exercise Purpose: This is a significant step up in logic. It introduces Recursion, the act of a function calling itself. This is the only clean way to handle “infinite” depth without knowing the structure ahead of time.

Given Input: Deep List: [1, [2, [3, 4], 5], 6, [7, 8]]

Expected Output: Flattened: [1, 2, 3, 4, 5, 6, 7, 8]

Hint
  • Loop through the items. If an item is a list, call the function again on that item.
  • If it’s an integer, just add it to your results.
Solution
def deep_flatten(lst):
    result = []
    for item in lst:
        if isinstance(item, list):
            # Recursively call the function and extend the result
            result.extend(deep_flatten(item))
        else:
            result.append(item)
    return result

# Test the function
complex_list = [1, [2, [3, 4], 5], 6, [7, 8]]
flat = deep_flatten(complex_list)

print(f"Deeply Nested: {complex_list}")
print(f"Fully Flattened: {flat}")Code language: Python (python)

Explanation to Solution:

  • isinstance(item, list): This checks if the current element is a list. If it is, we can’t just add it; we have to “dig deeper.”
  • result.extend(deep_flatten(item)): This is the recursive magic. The function pauses its current work to solve the inner list first, then adds that solved result to the current list.
  • Base Case: When the function hits an item that isn’t a list (an integer), it simply appends it and returns, effectively ending that branch of recursion.

Exercise 40. Calculate Cumulative Sum (Prefix Sums)

Practice Problem: Create a function that transforms a list of numbers into their cumulative sum. Each element at index i in the new list should be the sum of all elements from index 0 to i in the original list.

Exercise Purpose: Cumulative sums (or prefix sums) are used in financial tracking (running balance), signal processing, and algorithms that require quick range-sum queries. It teaches you how to maintain a Running Total.

Given Input: List: [10, 20, 30, 40]

Expected Output: Cumulative Sum: [10, 30, 60, 100]

Hint
  • Keep a variable called current_sum initialized to 0.
  • Iterate through the list, add the current element to current_sum, and append that total to a new list.
Solution
def cumulative_sum(nums):
    total = 0
    sums = []
    for n in nums:
        total += n
        sums.append(total)
    return sums

# Test the function
numbers = [10, 20, 30, 40]
result = cumulative_sum(numbers)

print(f"Original: {numbers}")
print(f"Cumulative: {result}")Code language: Python (python)

Explanation to Solution:

  • total += n: In each step of the loop, the “running total” absorbs the next value.
  • Efficiency: This is an O(n) operation because we only pass through the list once. Using a nested sum for every index (e.g., sum(nums[:i+1])) would be much slower (O(n2)).

Exercise 41. Rotate a List (Left or Right by k positions)

Practice Problem: Write a function to rotate a list to the left by k positions. For example, if k=2, the first two elements move to the end of the list.

Exercise Purpose: List rotation is a common algorithm in circular buffers and scheduling. This exercise teaches you how to use the Modulo Operator (%) to handle cases where k is larger than the list length, and how to perform complex reordering using Slicing.

Given Input:

  • List: [1, 2, 3, 4, 5]
  • k: 2

Expected Output: Rotated List: [3, 4, 5, 1, 2]

Hint
  • Use slicing to split the list at index k. The result is simply the second part of the list followed by the first part.
  • To handle k > length, use k = k % len(lst).
Solution
def rotate_left(lst, k):
    if not lst:
        return lst
    # Normalize k in case it's larger than the list length
    n = len(lst)
    k = k % n
    # Slice from k to end, then add slice from start to k
    return lst[k:] + lst[:k]

# Test the function
numbers = [1, 2, 3, 4, 5]
shift = 2
result = rotate_left(numbers, shift)

print(f"Original: {numbers}")
print(f"Left Rotated by {shift}: {result}")Code language: Python (python)

Explanation to Solution:

  • k = k % n: This ensures that if you rotate a list of length 5 by 7 positions, it behaves the same as rotating by 2 (7%5 = 2).
  • lst[k:]: This extracts the “tail” of the list starting from the rotation point.
  • lst[:k]: This extracts the “head” that is being pushed out.
  • By adding them (tail + head), you effectively wrap the beginning of the list around to the end.

Exercise 42. Split List into Chunks of Size N

Practice Problem: Create a function that takes a list and an integer N, and breaks the list into smaller sublists, each of length N. The last chunk may be shorter if the list length isn’t perfectly divisible by N.

Exercise Purpose: Batch processing is essential when dealing with large datasets or API limits (e.g., “send 50 emails at a time”). This exercise demonstrates the use of the Step Parameter in the range() function.

Given Input:

  • List: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • N: 3

Expected Output:

Chunks: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

Hint
  • Use a list comprehension that iterates through the list indices using range(0, len(lst), N).
  • In each iteration, slice the list from the current index to index + N.
Solution
def split_into_chunks(lst, n):
    # Iterate through the list in steps of n
    return [lst[i : i + n] for i in range(0, len(lst), n)]

# Test the function
my_data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
size = 3
chunks = split_into_chunks(my_data, size)

print(f"Original: {my_data}")
print(f"Chunks of {size}: {chunks}")Code language: Python (python)

Explanation to Solution:

  • range(0, len(lst), n): This generates numbers like 0, 3, 6, 9.... These serve as the starting boundaries for each chunk.
  • lst[i : i + n]: Python’s slicing is “forgiving.” If i + n is greater than the total length of the list, it simply stops at the end of the list rather than throwing an error. This automatically handles the final, smaller chunk.

Exercise 43. Move All Zeros to the End (Maintaining Order)

Practice Problem: Given a list of numbers, push all zeros to the end of the list while maintaining the relative order of all non-zero elements. This must be done efficiently.

Exercise Purpose: This “Stable Partitioning” problem is a favorite in technical interviews. It tests your ability to filter data based on a specific criterion while preserving the integrity of the remaining sequence.

Given Input: List: [0, 1, 0, 3, 12]

Expected Output: Result: [1, 3, 12, 0, 0]

Hint

The most straightforward way is to create two lists, one for non-zeros and one for zeros—and then join them.

Solution
def move_zeros(nums):
    # Filter non-zeros and zeros separately
    non_zeros = [x for x in nums if x != 0]
    zeros = [x for x in nums if x == 0]
    
    # Combine them
    return non_zeros + zeros

# Test the function
arr = [0, 1, 0, 3, 12]
result = move_zeros(arr)

print(f"Original: {arr}")
print(f"Zeros moved: {result}")Code language: Python (python)

Explanation to Solution:

  • Two-Pass Filtering: The first list comprehension extracts every number that isn’t zero, keeping them in their original order. The second does the same for zeros.
  • In-place Alternative: While the solution above uses extra memory (O(n) space), an in-place version would involve a pointer that keeps track of where the next non-zero should be written. However, for readability in Python, list comprehension is preferred.

Exercise 44. Generate Prime Numbers using List Comprehension

Practice Problem: Write a single list comprehension that generates a list of all prime numbers up to a given number n.

Prime number is a whole number greater than 1 that cannot be exactly divided by any whole number other than itself and 1 (e.g. 2, 3, 5, 7, 11).

Exercise Purpose: This exercise pushes your List Comprehension skills to the limit. It requires nesting logic and understanding the mathematical definition of a prime (a number x > 1 that has no divisors other than 1 and itself).

Given Input: n = 20

Expected Output: Primes: [2, 3, 5, 7, 11, 13, 17, 19]

Hint
  • A number x is prime if it is not in the set of “composite” numbers.
  • You can generate composite numbers by multiplying i * j for various ranges.
Solution
def get_primes(n):
    # A prime is any number not in the list of products (composites)
    composites = [j for i in range(2, 8) for j in range(i*2, n + 1, i)]
    primes = [x for x in range(2, n + 1) if x not in composites]
    return primes

# Test the function
limit = 20
result = get_primes(limit)

print(f"Primes up to {limit}: {result}")Code language: Python (python)

Explanation to Solution:

  • Composites Generation: The first comprehension mimics the Sieve of Eratosthenes. It finds multiples of numbers (starting from 2, 3, etc.) and marks them as composite.
  • x not in composites: This acts as a filter. If a number between 2 and $n$ was never flagged as a multiple of a smaller number, it must be prime.
  • Efficiency: While elegant, not in on a list is O(n). For massive ranges, converting composites to a set would drastically improve performance.

Exercise 45. Find All Subsets of a List (Power Set)

Practice Problem: Write a function to find the Power Set of a given list. The Power Set is a list of all possible subsets, including the empty list and the list itself.

Exercise Purpose: This introduces Combinatorial Logic. The number of subsets for a list of size n is always 2n. Mastering this is crucial for “Brute Force” algorithms where you need to test every possible combination of items.

Given Input: List: [1, 2, 3]

Expected Output:

Subsets: [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

Hint
  • Start with a list containing an empty list: [[]].
  • For every element in your original list, take all existing subsets and create new ones by adding the current element to them.
Solution
def get_power_set(lst):
    result = [[]]
    for element in lst:
        # For every existing subset, create a new one including the 'element'
        new_subsets = [subset + [element] for subset in result]
        result.extend(new_subsets)
    return result

# Test the function
base_list = [1, 2, 3]
subsets = get_power_set(base_list)

print(f"Original: {base_list}")
print(f"Power Set (Count {len(subsets)}): {subsets}")Code language: Python (python)

Explanation to Solution:

Iterative Building:

  1. Start with [[]].
  2. Add 1: Current subsets [] + new subset [1] = [[], [1]].
  3. Add 2: Current subsets [], [1] + new ones [2], [1, 2] = [[], [1], [2], [1, 2]].
  • This doubling effect continues for every element, resulting in exactly 2n subsets.
  • Order: This specific method generates subsets in a logical order, gradually increasing the complexity of the combinations.

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

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

All Coding Exercises:

C Exercises
C++ Exercises
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 25+ questions
  • Each Quiz contains 25 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
  • Intermediate Python Exercises
  • 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.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

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

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

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–2026 pynative.com