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.
- Use our Online Code Editor to solve these exercises in real time.
- Also, Solve Python Exercises: 29 topic-wise exercises with over 800+ coding questions
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
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]
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
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
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
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
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]
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]
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!)
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']
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]
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]
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
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
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
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]
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.
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]
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']
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]
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]
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']
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
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]
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]
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
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
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']
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
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]
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']
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
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'}
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]
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]
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']]
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']
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]
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]
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]
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]
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]]
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]
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]
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]]
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.

Under lists exercise, exercise 19
list1 = [10, 20, 30, 40]
list2 = [100, 200, 300, 400]
def iterate_list_simultaneously(a, b):
for x, y in zip(a, b):
print(x, y)
iterate_list_simultaneously(list1, list2[::-1])
instead of this
list1 = [10, 20, 30, 40]
list2 = [100, 200, 300, 400]
for x, y in zip(list1, list2[::-1]):
print(x, y)
Thank you Vishal, great site for Python.
For exercise 23 in List Exercise I found this way
list1 = [5, 10, 15, 20, 25, 50, 20]
def first_occurrence(list_name, number, replacement):
for i, n in enumerate(list_name):
if n == number:
list_name[i] = replacement.
break
return list_name
first_occurrence(list1, 20, 200)
[5, 10, 15, 200, 25, 50, 20]
Which is more general
Regards
this is more simple code for exercise 9:
a= [10, 20, 30]
b=[]
for i in a:
b.append(i)
print(“Original list:”,a,”\nCopied list:”,b)
isse better y sabse easy rahega !!
a=[10,20,30]
b=a[:]
print(“b”,b)
print(“a”,a)
Hi Vishal , I would like to tell you that I found the questions very helpful. I noticed that Exercise-2 will not give correct output if the length of the lists is different. Below is a correct program.
Exercise-2
list1 = [“M”, “na”, “i”, “Ke”,”Dan”,”San”]
list2 = [“y”, “me”, “s”, “lly”]
length=len(list1) if len(list1)len(list2) else list2
new_list=list()
for i in range(length):
new_list.append(list1[i]+list2[i])
new_list.extend(larger_list[length:])
print(new_list)
sorry, I made an error when I copy and paste.
The correct program is
list1 = [“M”, “na”, “i”, “Ke”,”Dan”,”San”]
list2 = [“y”, “me”, “s”, “lly”]
length=len(list1) if len(list1)len(list2) else list2
new_list=list()
for i in range(length):
new_list.append(list1[i]+list2[i])
new_list.extend(larger_list[length:])
print(new_list)
I don’t know why it is not pasted correctly but the following line of code is above the for loop.
larger_list=list1 if len(list1)>len(list2) else list2
The third line is
length=len(list1) if len(list1)<len(list2) else len(list2)
Please consider if inequalities are missed when I paste the code.
#EXERCISE -8 :
list1 = [“a”, “b”, [“c”, [“d”, “e”, [“f”, “g”], “k”], “l”], “m”, “n”]
sub_list = [“h”, “i”, “j”]
#METHOD -1 using loop and indexing and append
for i in sub_list:
list1[2][1][2].append(i)
print(list1)
if u use append() a new list will b created inside that list , so it will be nested , that’s y use extend() the value will insert inside the list
A solution with readable code:
list1 = [5, 20, 15, 20, 25, 50, 20]
print(“Original List”,list1)
list2=[]
numberPresent=[]
if list1.count(20) > 1:
for i in range(0,len(list1)):
if list1[i] != 20:
list2.append(list1[i])
else:
numberPresent.append(i)
else:
print(“The number to be removed should be there more than once”)
print(“New list:”,list2)
print(“The removed 20 is present in indexes:”,numberPresent)
list1 = [5, 20, 15, 20, 25, 50, 20]
print(“Original List”,list1)
list2=[]
numberPresent=[]
if list1.count(20) > 1:
for i in range(0,len(list1)):
if list1[i] != 20:
list2.append(list1[i])
else:
numberPresent.append(i)
print(“New list:”, list2)
print(“The removed 20 is present in indexes:”, numberPresent)
else:
print(“The number to be removed should be there more than once”)
last 2 lines(print statements) can be put within first ‘if’ block from the beginning
Exercise 10:
for item in list1:
if item == 20:
list1.remove(item)
i wont work because remove() methos used to remove single value at time
so u need to use slicing [ : ] it wil iterate from 0 index to -1
below is code
lis =[5, 20, 15, 20, 25, 50, 20]
for item in lis[:]:
if item == 20:
lis.remove(item)
print(lis)
Exercise 9:
for i, item in enumerate(list1):
if item == 20:
list1[i]=200
break
exercises 6;
new_list =[]
list1 = [“Mike”, “”, “Emma”, “Kelly”, “”, “Brad”]
for w in list1:
if w == “”:
continue
else:
new_list.append(w)
print(new_list)
exercises 4
new_list = []
list1 = [“Hello “, “take “]
list2 = [“Dear”, “Sir”]
for x in list1:
for y in list2:
new_list.append(x + y)
print(new_list)
Maybe more like that:
new_list = []
list1 = [“Hello”, “take”]
list2 = [“Dear”, “Sir”]
for x in list1:
for y in list2:
new_list.append(x + ” ” + y)
print(new_list)
I just added the quotations between x and y so there will be space between the words.
exercise 3;
i = 0
new_list = [ ]
for x in list1:
y = x + list2[i]
new_list.append(y)
i += 1
print(new_list)
exercises 1:
for x in range (-1, -Len(list1)-1, -1):
print(list1[x], end = ” “)
Exercise 8:
def add_sublist_in_list(l, sub_l):
for i in l:
if isinstance(i, list) and i[-1] == “g”:
i.extend(sub_l)
elif isinstance(i, list):
add_sublist_in_list(i, sub_l)
list1 = [“a”, “b”, [“c”, [“d”, “e”, [“f”, “g”], “k”], “l”], “m”, “n”]
# sub list to add
sub_list = [“h”, “i”, “j”]
add_sublist_in_list(list1, sub_list)
print(list1)
Q 10. ALTERNATIVE ANSWER
list1 = [5, 20, 15, 20, 25, 50, 20]
for i in list1:
if i == 20:
list1.remove(i)
print(list1)
Q5 Alternate Answer
list1 = [10, 20, 30, 40]
list2 = [100, 200, 300, 400]
for i in range(len(list1)):
print(f'{list1[i]} {list2[-(i+1)]}’)
print()
Q3 Alternate Answer
numbers = [1,2,3,4,5,6,7]
for i in range(len(numbers)):
numbers[i] = numbers[i] ** 2
print(numbers)
Q7. Another solutions:
list1[2][2].insert(2, 7000)
print(list1)
***************************************************************************************
list1[2][2].extend([7000])
print(list1)
Q10. Alternative answer:
list1 = [5, 20, 15, 20, 25, 50, 20]
b = []
def myFunc(list1):
for x in list1:
if x 20:
b.append(x)
return b
res = myFunc(list1)
print(res)
Q6. Alternative answers:
list1 = [“Mike”, “”, “Emma”, “Kelly”, “”, “Brad”, None]
res = []
for i in list1:
if i:
res.append(i)
print(res)
***************************************************************
res = [i for i in list1 if i]
print(res)
Q6 Alternate Answer
list1 = [“Mike”, “”, “Emma”, “Kelly”, “”, “Brad”]
i = len(list1) – 1
while i > -1:
if list1[i] == “”:
list1.remove(list1[i])
i = i – 1
print(list1)
Q3. Alternative answer:
numbers = [1, 2, 3, 4, 5, 6, 7]
res = list(map(lambda x: x ** 2, numbers))
print(res)
good job, thank you for exersices
#Remove all occurrences of a specific item from a list.list1 = [5, 20, 15, 20, 25, 50, 20]
for x in list1:
if 20 in list1:
list1.remove(20)
print(list1)
list1 = [5, 20, 15, 20, 25, 50, 20]
result = []
for i in list1:
if i != 20:
result.append(i)
print(result)
while 20 in list1:
list1.remove(20)
print(list1)
instead
x = set(list1)
print(x)
I think we would simply do like this:
print(list(set(list1)))
list1 = [200 if x==20 else x for x in list1]
print(list1)
#7
An example solution is a pure shame.
Here is normal one:
list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]def func(list):
for i in list:
if type(i) == list and i[-1] == 6000: i.append(7000)
elif type(i) == list: func(i)
func(list1)print(list1)
upd (i shouldn’t have renamed the argument)
list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]def func(l):
for i in l:
if type(i) == list and i[-1] == 6000: i.append(7000)
elif type(i) == list: func(i)
func(list1)print(list1)
Exercise 7: Simple Solution
def add_item(l):
for i in l:
if isinstance(i, list) and i[-1] == 6000:
i.append(7000)
elif isinstance(i, list):
# if ‘i’ is list then again call the function
add_item(i)
list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]
add_item(list1)
print(list1)
thank you
# 1: Reverse a list in Pythonlist1 = [100, 200, 300, 400, 500]
list1.reverse()
print(list1)
# 2: Concatenate two lists index-wise
list1 = ["M", "na", "i", "Ke"]
list2 = ["y", "me", "s", "lly"]
list3 = [i+j for i,j in zip(list1,list2)]
print(list3)
# 4: Concatenate two lists in the following order.
list1 = ["Hello ", "Bye "]
list2 = ["Sir", "Dear"]
print([i+j for i in list1 for j in list2])
# 5: Iterate both lists simultaneously.
list1 = [10, 20, 30, 40]
list2 = [100, 200, 300, 400]
for i , j in zip(list1,list2[::-1]):
print(i,j)
# 6: Remove empty strings from the list of strings.
list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"]
list1.remove("")
list1.remove("")
print(list1)
# 7: Add new item to list after a specified item
# add item 7000 after 6000
list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]
list1[2][2].append(7000)
print(list1)
# 8: Extend nested list by adding the sublist
# adding the sublist ["h", "i", "j"] after "f", "g".
list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]
sub_list = ["h", "i", "j"]
list1[2][1][2].extend(sub_list)
print(list1)
# 9: Replace list’s item with new value if found.
# find value 20 in the list, and if it is present, replace it with 200.
list1 = [5, 10, 15, 20, 25, 50, 20]
a = list1.index(20)
list1[a] = 200
print(list1)
# 10: Remove all occurrences of a specific item from a list.# remove all occurrences of item 20.
list1 = [5, 20, 15, 20, 25, 50, 20]
print([i for i in list1 if i != 20])
# 3: Turn every item of a list into its squarenumbers = [1, 2, 3, 4, 5, 6, 7]
print([i*i for i in numbers])
Exercise number 3
numbers = [1, 2, 3, 4, 5, 6, 7]for index, item in enumerate(numbers):
numbers[index] = item ** 2
print(numbers)Exercise 1
list1 = [100, 200, 300, 400, 500]increase_position = 0
for ele, value in enumerate(range(0, len(list1))):
last_ele = list1[-1]
list1.remove(list1[-1])
list1.insert(increase_position, last_ele)
increase_position += 1
print(list1)Exercise 2 – model solution adapted for 2 lists of different lengths
(please indent code as appropriate – tags don’t seem to work on my posts)
I propose this solution based on a functional approach for exercise number three:
‘list’ object is not callable
you can just write like this :
l1=[]for i in list1:
if len(i)!=0:
l1.append(i)
print(l1)Question:6
what if list1 has None value?
An alternate way of step 1:-
An alternate solution to Exercise 3.
Thanks for this site
exercise 1 in 3 different ways
exercise 6 :
why this wrong?
list1 = ["M", "na", "i", "Ke"]list2 = ["y", "me", "s", "lly"]
listf = []
for i in range(4):
listf.append(list1[i] + list2[i])
print(listf)exercise 3
why make it hard
just do
output = [x*x for x in numbers]its q. 10
Question 3
As a begginer I tried this and it worked also
Sorry bro, but your code does not work.
I changed it to the correct version
Here is it:
ex 10
Exercise 5:
Exercise 4:
exercise 10:
Question 6 with list comprehension
For Question 3 using list comprehension
Thanks, it was a simple and useful exercise 😄️💜️
Hello, For Q3: Turning every item of a list into its square,
Q6
Or you can use list comprehension
it goes like this:
l1 = ["Mike", "", "Emma", "Kelly", "", "Brad"]res = [i for i in l1 if i]
print(res)
Question 2
if l2 length is more then extra element is not added in list
yes try this one
This is a good one.
For Exercise 3: I applied this code, but for some reason on the results, it gives me [1, 16, 9, 4, 25, 36, 49]. Could anyone bother explaining to me why?
The function index() takes as a parameter the value of the item in the list and returns the index. If you add
print()inside the loop you will understand what is going wrong. If you run this:you get the following:
This mean that when your i is 4 your list is
[1, 4, 9, 4, 5, 6, 7]So the
numbers.index(i)returns the position of the second item in the list that is the first 4 right now so [1]. And then it changes is to 16.Exercise 3: Turn every item of a list into its square
Given a list of numbers. write a program to turn every item of a list into its square.
Given:
Question 10
One simplest method.
Question 9
I don’t completely agree with the solution provided, because the question say item 20 if found. what if it’s not found then the solution will throw a “ValueError: Item not in list” Error. I’d go with iterating the list and update the item if found. I would suggest the solution below instead.
Sorry I couldn’t find a way to use the
index()function which is the aim of this exerciseInstead of range() you could use enumerate, to avoid finding the length of the list and an arithmetic operation. Like below,
Correct me if am wrong
Question 1
voooowww! Your articles and exercises are helpful. Thanks alot.
Thank you for the great contents, i have learn a lot.
for problem 10, can we do this:
How to get the output from this list as below :
Hey just wanted to say thanks! These are very helpful for newbies like me 🙂
I am glad it helped you, Jenna.
how can I have your contact
Q10
FOR EXERCISE 8, another different(not so different) approach:
EXERCISE 4:
#my idea was to use nested loops: Each time the i block run, the j block runs 2 times. 2 times because that’s the length of the list and that’s how much we will go through the list.
Another approach for exercise2:
exercise3*** .My bad!
FOR EXERCISE 1:
#my idea was to start counting from the end of the list going down by 1, at the same time,I am adding the value at that position into a new list
exercise6:
ex 10
Is this right for ex 10?
For exercise 5, it is also possible to do it this way:
Thank you for the alternative solution, Leonardo.
For 10
another way:
For Exercise 6 :
For Ex:5 I am not using the Zip function as I have not learned it yet. It a long way, but works
Hi,
for Ex3:
How do I modify this code to get the right o/p?
problem = 3
Hi,
For Ex:2:
this following code id giving me right output. But can somebody tell me the best practice please..
Thanks Hinata 🙂
Thanks khadim. I understood my fault now 🙂
From Naruto Uzumaki
thank you
do one thing
Anybody else has trouble not doing things the hard way? Here’s my solution for problem 4. Yours was so much simpler!
Hi there,
I recommend this solution for problem 10 in the list exercise
list1 = [5, 20, 15, 20, 25, 50, 20] while 20 in list1: list1.remove(20)hey dude! how to generate this program??
“Program to generate the sequence: -5,10, -15,20, -25 ——up to n terms”
try this
it won’t give the required list:
enter a number25
5 -5 -15 -25 25
this is how it gives result
ok thanks
hows mine?
Here is my solution in two methods:
method-1:
method-2:
Exercise 10: Given a Python list, remove all occurrence of 20 from the list
Result: [5, 15, 25, 50]
if you have multiple 20s , there will be a logic error
I don’t get a logic error
Code:
Output:
please tell how we decide dimension as in ques 8 list[2][1][2]
Index value for question 8:
I hope this might help u
Problem 1:
Other Approach:- The Below also works
Another solution for Q6
Hi all! this code should remove all negative values from the given list and print a new list with only positive values for some reason it prints an iteration of the given list before the positive list. can I get any hints on how to solve that, please?
you have to add at the end of your def a return statement:
return listOfIntegers
Alternative answer for Q10:
list1 = [5, 20, 15, 20, 25, 50, 20] for x in list1: if x == 20: list1.remove(20) print(list1)Alternative answer for Q10:
One another:
Here’s another
Can anyone please point out the mistake, or is this code correct…..
you must loop over the remove function in order to work
your program is correct.it is running without any error
[5,10,15,300,25,50,20]
Any alternative ans for Q-2
question no.10
Thanks..it really helps:-)
Questions 4:
Any alternate answers for Q-10
Here is an alternate solution for question no.10
Alternative answer to Q9 — Note: would have convert back to a list to satisfy the question requirements.
Thanks Vishal, I am a beginner level python learner and I am doing the exercises , I found these helpful because these cover many methods of data structure and challenges as well. I enjoy solving them.
You’re welcome, Qadeer Rizvi.
sir your article are amazing very helpful for me.keep it up and live long
Thank you, Bostan Khan, for your kind words
list1[2][1][2].extend(subList)i can’t understand the indexing value.please heip me out.
I also had a problem with that. I printed all values in order to understand and it helped me.
Try first print:
list1[0]
then look at
list1[1]
then try
list1[0][0]
then
list1[1][0]
etc.
If you will see it then it will be easier to understand indexing.
can you explain Q4 flow of code not able to understand
its work like nested loop,which mean for each iteration of outer loop the inner loop will be executed completely.keep in mind nested loop and execute it then you guess easily
Good Work Vishal !! Do you run any online classes for Python. I am ready to join in your class
Hey Prashanth, I am not running any classes as of now. I will definitely let you know once I started it.
Hi team,
I’m having trouble understanding the specific append questions where you have to place an item inside a specific list (Q7, Q8). Is there a trick people use to figure out how the indexing associated with the lists work? Playing around, it seems most the index changes result in an error.
Thanks!
Question 7
Question 8
I don’t understand the index of lists. Where they come from? Does someone want to explain?
its like array indexing access ,the point here to be noted each list in the list will be consider an element of the list
Hey Marcin
Just count values in first index, then in second, until you reach the destination index to apply append/extend function.
lets say in Q7.
there are two values in first index before second index initiate so use 2 for that, then again we have 2 values in second index before 3rd and destination index start so use 2 again. Now you can use append function here which is third index.
for question1, can we use the below code?
start = 100 stop = 500 step = 100 stop += step for i in reversed(range(start, stop, step)): print(i, end=" ")which gives the same output as expected, maybe a lengthy code but just want to know whether we can use this method
Thanks in advance
The idea is to use the existing data and you need to supply method. If the data change, for example is has no uniform step interval, then your code fails.
question 5: i think this method is more easy and if this method is not preferred then pls reply
list1 = [10,20,30,40] list2 = [100,200,300,400] l2.reverse() for value in range(len(l1)): print(list1[value],list2[value])Hi, great collection of exercises. For question 7 is there any way to run a loop and extract all the elements while ignoring the sub-lists ?
Hey Noma, Please use the following code
list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40] for i in list1: if isinstance(i, list): continue else: print(i)Thanks sir it gave a lot of help to me. Thanks again
Thank you Vishal – This is by far the best website on python for practise,
request to share anylinks or references to read furtheron python topics for begineers
Thank you, Pallavi. Within two weeks you will see new topics for beginners on PYnative
Please tell me the difference between lists and tuples.
lists are mutable whereas tuples are immutable.