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
- Access the third element of a list
- List Length: Print the total number of items
- 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) == 0or simply use the list’s boolean value.
Solution
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 inO(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,” meaningif 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:
- Change Element: Change the second element of a list to 200 and print the updated list.
- Append Element: Add 600 o the end of a list and print the new list.
- Insert Element: Insert 300 at the third position (index 2) of a list and print the result.
- Remove Element (by value): Remove 600 from the list and print the list.
- Remove Element (by index): Remove the element at index 0 from the list print the list.
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] = valuefor updates, .append()for the end,.insert(index, value)for specific spots,- and
.remove()or.pop()for deletions.
Solution
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 aValueError..pop(0): Unlikeremove,popworks 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
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 manualforloop.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
Explanation to Solution:
max()andmin(): 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
Solution
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 forproduct = 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
Explanation to Solution:
num % 2 == 0: This checks the remainder ofnum/2. If the remainder is 0, the logic path for “Even” executes.- Counters: We initialize
even_countandodd_countat 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
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
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
Explanation to Solution:
- By using
.copy(), we allocate a new block of memory fornew_copy. When we add “Date” to it, theoriginalremains 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 thecopymodule’sdeepcopy()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
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 originallist_a, you would uselist_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
stopindex in a slice is exclusive. - To get elements at indices 2, 3, and 4, your slice needs to go from 2 to 5.
Solution
Explanation to Solution:
sample_list[2:5]: This grabs items atindex 2,index 3, andindex 4.
Exclusive Bound: Python stops before the second number. A good trick to remember:stop - startequals 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:
0and2
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
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 = templogic, 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
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
Explanation to Solution:
inOperator: Behind the scenes, Python iterates through the list and compares each item to your target.
Performance Note: For a list, this isO(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 asetforO(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
Explanation to Solution:
key=len: This tells themax()function: “Don’t find the ‘largest’ word alphabetically; find the one where thelen()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
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
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
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_vintact, 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 toFalse, so you can just check the truthiness of the string.
Solution
Explanation to Solution:
filter(None, names): Thefilterfunction is highly efficient for large datasets. PassingNoneas the first argument tells Python to remove anything that is not “Truthy.”list():filterreturns an “iterator” (to save memory). We wrap it inlist()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
setcannot 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
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
Explanation to Solution:
if x % 2 == 0: This condition acts as a “bouncer.” The variablexis 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
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
Explanation to Solution:
- Unpacking: The
x, ysyntax “unpacks” the tuple returned byzipat each step, making the variables immediately available without extra indexing. - Synchronization: This ensures that
xandyalways 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()atindex + 1.
Solution
Explanation to Solution:
list1.index(30): Returns2.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
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 aValueErrorand crash your program.- In-place Modification: This directly changes
list1rather 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
Explanation to Solution:
set(nums): This constructor removes all duplicate values. Without this, a list like[35, 35, 10]would incorrectly identify35as 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, index1is 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
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
stepparameter.
Solution
Explanation to Solution:
lst[::n]: The double colons tell Python to include the full range of the list (from start to end). Thenat 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
forloop 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
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
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
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 stringsand place it into the new resulting list only if it passes theifcheck.
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 tolist[i + 1]. - You can use the
all()function combined with a generator expression for a clean solution.
Solution
Explanation to Solution:
range(len(lst) - 1): We stop one element before the end so thatlst[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 returnsTrueonly if every single comparison in the loop isTrue. If even one pair is out of order, it immediately returnsFalse.
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
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
Explanation to Solution:
set(list_b): By makinglist_ba set, Python can checkif item not in excludedalmost instantly, regardless of how largelist_bis.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
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
forloop to grab each sublist. - Once you have a reference to the sublist, use the
.append()method to add the new value.
Solution
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 tosublistmodifies the original inner list insidedata.- 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
forclauses. - The first
foriterates through List 1, and the secondforiterates through List 2 for every item in the first.
Solution
Explanation to Solution:
for x in list1 for y in list2: This works like a nested loop. For the first item inlist1(“Hello “), it runs through all items inlist2. Then it moves to the second item inlist1(“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
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
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_suminitialized to 0. - Iterate through the list, add the current element to
current_sum, and append that total to a new list.
Solution
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, usek = k % len(lst).
Solution
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
Explanation to Solution:
range(0, len(lst), n): This generates numbers like0, 3, 6, 9.... These serve as the starting boundaries for each chunk.lst[i : i + n]: Python’s slicing is “forgiving.” Ifi + nis 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
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
xis prime if it is not in the set of “composite” numbers. - You can generate composite numbers by multiplying
i * jfor various ranges.
Solution
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 inon a list isO(n). For massive ranges, convertingcompositesto asetwould 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
Explanation to Solution:
Iterative Building:
- Start with
[[]]. - Add
1: Current subsets[]+ new subset[1]=[[], [1]]. - 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.
