PYnative

Python Programming

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

Python list Exercises: 45 Coding Problems with Solutions

Updated on: June 13, 2026 | 210 Comments

This article provides 45 Python list practice questions with solutions.

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

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

  • All solutions have been fully tested on Python 3.
  • 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

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

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

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

Expected Output:

Third element: 30
Length of list: 5
Is the list empty? False
Solution
sample_list = [10, 20, 30, 40, 50]

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

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

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

Explanation to Solution:

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

Exercise 2. Perform List Manipulation

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

  1. Change Element: Change the second element of a list to 200 and print the updated list.
  2. Append Element: Add 600 o the end of a list and print the new list.
  3. Insert Element: Insert 300 at the third position (index 2) of a list and print the result.
  4. Remove Element (by value): Remove 600 from the list and print the list.
  5. Remove Element (by index): Remove the element at index 0 from the list print the list.

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

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

Expected Output:

Updated (Change): [100, 200, 400, 500]
Updated (Append): [100, 200, 400, 500, 600]
Updated (Insert): [100, 200, 300, 400, 500, 600]
Updated (Remove 600): [100, 200, 300, 400, 500]
Updated (Remove Index 0): [200, 300, 400, 500]
Solution
list_m = [100, 50, 400, 500]

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

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

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

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

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

Explanation to Solution:

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

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

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

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

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

Expected Output:

Sum: 150
Average: 30.0
Solution
nums = [10, 20, 30, 40, 50]

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

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

Explanation to Solution:

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

Exercise 4. Find Maximum and Minimum from List

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

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

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

Expected Output:

Maximum: 89
Minimum: 2
Solution
data_points = [45, 12, 89, 2, 67]

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

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

Explanation to Solution:

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

Exercise 5. Calculate the Product of All Elements

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

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

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

Expected Output: Product: 210

Solution
factors = [2, 3, 5, 7]
product = 1

for x in factors:
    product *= x

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

Explanation to Solution:

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

Exercise 6. Count Even and Odd Numbers

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

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

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

Expected Output:

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

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

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

Explanation to Solution:

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

Exercise 7. Reverse a List

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

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

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

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

Solution
list1 = [100, 200, 300, 400, 500]

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

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

Explanation to Solution:

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

Exercise 8. Sort a List of Numbers

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

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

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

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

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

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

Explanation to Solution:

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

Exercise 9. Create a Copy of a List

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

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

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

Expected Output:

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

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

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

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

Explanation to Solution:

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

Exercise 10. Combine Two Lists

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

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

Given Input:

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

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

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

# Combine using the + operator
combined = list_a + list_b

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

Explanation to Solution:

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

Exercise 11. List Slicing: Extract Middle Elements

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

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

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

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

Solution
sample_list = [10, 20, 30, 40, 50, 60, 70]

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

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

Explanation to Solution:

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

Exercise 12. Swap Two Elements at Given Indices

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

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

Given Input:

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

Expected Output:

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

print(f"Original: {list_data}")

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

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

Explanation to Solution:

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

Exercise 13. Access Nested Lists (Simple Indexing)

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

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

Given Input:

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

Expected Output: Accessed Value: 5

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

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

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

Explanation to Solution:

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

Exercise 14. Check if List Contains a Specific Item

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

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

Given Input:

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

Expected Output: Is Tablet in inventory? False

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

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

Explanation to Solution:

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

Exercise 15. Find the Longest String in a List

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

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

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

Expected Output: Longest word: Exercises

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

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

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

Explanation to Solution:

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

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

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

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

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

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

Solution
numbers = [1, 2, 3, 4, 5]

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

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

Explanation to Solution:

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

Exercise 17. Count Occurrences of an Item

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

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

Given Input:

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

Expected Output: The number 10 appears 3 times.

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

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

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

Explanation to Solution:

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

Exercise 18. Remove All Occurrences of a Specific Item

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

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

Given Input:

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

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

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

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

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

Explanation to Solution:

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

Exercise 19. Remove Empty Strings from a List of Strings

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

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

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

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

Solution
names = ["Mike", "", "Emma", "Kelly", "", "Brad"]

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

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

Explanation to Solution:

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

Exercise 20. Remove Duplicates from List

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

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

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

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

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

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

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

Explanation to Solution:

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

Exercise 21. List Comprehension for Filtering Numbers

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

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

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

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

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

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

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

Explanation to Solution:

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

Exercise 22. Concatenate Two Lists Index-wise

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

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

Given Input:

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

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

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

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

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

Explanation to Solution:

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

Exercise 23. Iterate Both Lists Simultaneously

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

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

Given Input:

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

Expected Output:

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

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

Explanation to Solution:

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

Exercise 24. Add New Item After a Specified Item

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

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

Given Input:

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

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

Solution
list1 = [10, 20, 30, 40, 50]
target = 30
new_val = 35

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

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

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

Explanation to Solution:

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

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

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

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

Given Input:

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

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

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

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

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

Explanation to Solution:

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

Exercise 26. Find the Second Largest Number in a List

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

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

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

Expected Output: Second Largest: 34

Solution
def get_second_largest(nums):
    # Remove duplicates by converting to a set
    unique_nums = list(set(nums))
    
    if len(unique_nums) < 2:
        return None
    
    # Sort the list in descending order
    unique_nums.sort(reverse=True)
    
    # Return the second element
    return unique_nums[1]

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

Explanation to Solution:

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

Exercise 27. Find the Most Frequent Element

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

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

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

Expected Output: Mode: 3

Solution
def find_mode(arr):
    frequency = {}
    
    # Count occurrences of each element
    for item in arr:
        frequency[item] = frequency.get(item, 0) + 1
    
    # Find the key with the maximum value
    mode = max(frequency, key=frequency.get)
    return mode

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

Explanation to Solution:

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

Exercise 28. Extract Every Nth Element from a List

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

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

Given Input:

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

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

Solution
def extract_nth(lst, n):
    # Using list slicing with a step of n
    return lst[::n]

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

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

Explanation to Solution:

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

Exercise 29. Check if List is Palindrome

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

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

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

Expected Output: Is Palindrome: True

Solution
def is_palindrome(lst):
    # Compare the list to its reverse
    return lst == lst[::-1]

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

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

Explanation to Solution:

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

Exercise 30. Find All Common Elements Between Three Lists

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

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

Given Input:

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

Expected Output: Common Elements: [20]

Solution
def find_common(list1, list2, list3):
    # Convert lists to sets and find the intersection
    common = set(list1) & set(list2) & set(list3)
    
    # Convert back to list to match expected output format
    return list(common)

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

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

Explanation to Solution:

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

Exercise 31. Filter Strings by Length in a List

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

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

Given Input:

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

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

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

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

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

Explanation to Solution:

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

Exercise 32. Check if List is Sorted

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

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

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

Expected Output: Is Sorted: False

Solution
def is_list_sorted(lst):
    # Check if every element is <= the next element
    return all(lst[i] <= lst[i + 1] for i in range(len(lst) - 1))

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

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

Explanation to Solution:

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

Exercise 33. List to Dictionary Conversion

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

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

Given Input:

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

Expected Output:

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

Solution
def lists_to_dict(keys, values):
    # Zip pairs the elements, dict() converts pairs to key-value entries
    return dict(zip(keys, values))

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

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

Explanation to Solution:

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

Exercise 34. Find the Difference Between Two Lists

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

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

Given Input:

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

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

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

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

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

Explanation to Solution:

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

Exercise 35. Remove Negative Numbers In-place

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

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

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

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

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

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

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

Explanation to Solution:

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

Exercise 36. Extend Nested List by Adding a Sublist

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

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

Given Input:

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

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

Solution
def extend_nested(nested_list, item):
    for sublist in nested_list:
        sublist.append(item)
    return nested_list

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

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

Explanation to Solution:

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

Exercise 37. Concatenate Two Lists in a Specific Order

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

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

Given Input:

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

Expected Output:

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

Solution
def specific_concat(list1, list2):
    # Nested list comprehension for item-wise combination
    return [x + y for x in list1 for y in list2]

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

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

Explanation to Solution:

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

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

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

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

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

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

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

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

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

Explanation to Solution:

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

Exercise 39. Flatten a Deeply Nested List (Recursion)

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

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

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

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

Solution
def deep_flatten(lst):
    result = []
    for item in lst:
        if isinstance(item, list):
            # Recursively call the function and extend the result
            result.extend(deep_flatten(item))
        else:
            result.append(item)
    return result

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

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

Explanation to Solution:

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

Exercise 40. Calculate Cumulative Sum (Prefix Sums)

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

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

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

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

Solution
def cumulative_sum(nums):
    total = 0
    sums = []
    for n in nums:
        total += n
        sums.append(total)
    return sums

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

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

Explanation to Solution:

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

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

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

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

Given Input:

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

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

Solution
def rotate_left(lst, k):
    if not lst:
        return lst
    # Normalize k in case it's larger than the list length
    n = len(lst)
    k = k % n
    # Slice from k to end, then add slice from start to k
    return lst[k:] + lst[:k]

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

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

Explanation to Solution:

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

Exercise 42. Split List into Chunks of Size N

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

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

Given Input:

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

Expected Output:

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

Solution
def split_into_chunks(lst, n):
    # Iterate through the list in steps of n
    return [lst[i : i + n] for i in range(0, len(lst), n)]

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

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

Explanation to Solution:

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

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

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

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

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

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

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

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

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

Explanation to Solution:

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

Exercise 44. Generate Prime Numbers using List Comprehension

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

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

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

Given Input: n = 20

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

Solution
def get_primes(n):
    # A prime is any number not in the list of products (composites)
    composites = [j for i in range(2, 8) for j in range(i*2, n + 1, i)]
    primes = [x for x in range(2, n + 1) if x not in composites]
    return primes

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

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

Explanation to Solution:

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

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

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

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

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

Expected Output:

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

Solution
def get_power_set(lst):
    result = [[]]
    for element in lst:
        # For every existing subset, create a new one including the 'element'
        new_subsets = [subset + [element] for subset in result]
        result.extend(new_subsets)
    return result

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

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

Explanation to Solution:

Iterative Building:

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

深圳市网捷达科技有限公司 联系电话:18910898173;

ICP备案号:粤ICP备2024312167号-2

Copyright © 网捷达 版权所有

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

TweetF  sharein  shareP  Pin

About Vishal

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

Related Tutorial Topics:

Python Python Basics Python Exercises

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

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

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

Comments

  1. Oladejo Olasunkanmi says

    January 16, 2026 at 12:11 am

    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)

    Reply
  2. Alessandro Turco says

    January 9, 2026 at 8:55 pm

    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

    Reply
  3. Abhishek Jamdade says

    July 8, 2025 at 10:31 pm

    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)

    Reply
    • jatin mulani says

      January 28, 2026 at 10:12 pm

      isse better y sabse easy rahega !!
      a=[10,20,30]
      b=a[:]
      print(“b”,b)
      print(“a”,a)

      Reply
  4. Okbazghi says

    January 30, 2025 at 2:37 pm

    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)

    Reply
    • Okbazghi says

      January 30, 2025 at 2:43 pm

      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)

      Reply
      • Okbazghi says

        January 30, 2025 at 2:56 pm

        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.

        Reply
  5. Surya Vamsi says

    August 28, 2024 at 9:32 pm

    #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)

    Reply
    • Ibtesham Akhtar says

      September 14, 2024 at 7:52 pm

      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

      Reply
  6. karthik says

    July 6, 2024 at 11:00 pm

    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)

    Reply
    • karthik says

      July 6, 2024 at 11:08 pm

      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”)

      Reply
    • karthik says

      July 6, 2024 at 11:11 pm

      last 2 lines(print statements) can be put within first ‘if’ block from the beginning

      Reply
  7. Flor77 says

    April 13, 2024 at 11:04 pm

    Exercise 10:

    for item in list1:
    if item == 20:
    list1.remove(item)

    Reply
    • Ibtesham Akhtar says

      September 14, 2024 at 7:57 pm

      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)

      Reply
  8. Flor77 says

    April 13, 2024 at 10:58 pm

    Exercise 9:

    for i, item in enumerate(list1):
    if item == 20:
    list1[i]=200
    break

    Reply
  9. ali says

    December 6, 2023 at 10:37 pm

    exercises 6;
    new_list =[]
    list1 = [“Mike”, “”, “Emma”, “Kelly”, “”, “Brad”]
    for w in list1:
    if w == “”:
    continue
    else:
    new_list.append(w)
    print(new_list)

    Reply
  10. ali says

    December 6, 2023 at 9:06 pm

    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)

    Reply
    • Mikey says

      May 6, 2024 at 7:25 am

      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.

      Reply
  11. ali says

    December 6, 2023 at 6:07 pm

    exercise 3;
    i = 0
    new_list = [ ]
    for x in list1:
    y = x + list2[i]
    new_list.append(y)
    i += 1
    print(new_list)

    Reply
  12. ali says

    December 6, 2023 at 2:54 pm

    exercises 1:
    for x in range (-1, -Len(list1)-1, -1):
    print(list1[x], end = ” “)

    Reply
  13. NS says

    November 27, 2023 at 2:01 pm

    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)

    Reply
  14. Sayi says

    November 21, 2023 at 11:22 am

    Q 10. ALTERNATIVE ANSWER
    list1 = [5, 20, 15, 20, 25, 50, 20]

    for i in list1:
    if i == 20:
    list1.remove(i)

    print(list1)

    Reply
  15. Jeremy Okyere says

    November 19, 2023 at 6:29 am

    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()

    Reply
  16. Jeremy Okyere says

    November 19, 2023 at 6:25 am

    Q3 Alternate Answer

    numbers = [1,2,3,4,5,6,7]
    for i in range(len(numbers)):
    numbers[i] = numbers[i] ** 2
    print(numbers)

    Reply
  17. fateme says

    November 16, 2023 at 8:42 am

    Q7. Another solutions:

    list1[2][2].insert(2, 7000)
    print(list1)

    ***************************************************************************************

    list1[2][2].extend([7000])
    print(list1)

    Reply
  18. fateme says

    November 15, 2023 at 12:23 pm

    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)

    Reply
  19. fateme says

    November 15, 2023 at 11:56 am

    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)

    Reply
    • Jeremy Okyere says

      November 19, 2023 at 6:23 am

      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)

      Reply
  20. fateme says

    November 15, 2023 at 11:36 am

    Q3. Alternative answer:

    numbers = [1, 2, 3, 4, 5, 6, 7]

    res = list(map(lambda x: x ** 2, numbers))
    print(res)

    Reply
  21. mohammadho3ein says

    August 21, 2023 at 11:36 am

    good job, thank you for exersices

    Reply
  22. Pramod kose says

    April 1, 2023 at 10:21 pm

    #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)

    Reply
    • Radii Temirgaliev says

      August 13, 2023 at 10:56 pm

      list1 = [5, 20, 15, 20, 25, 50, 20]
      result = []
      for i in list1:
      if i != 20:
      result.append(i)
      print(result)

      Reply
      • shubham shivhare says

        August 22, 2023 at 3:58 pm

        while 20 in list1:
        list1.remove(20)
        print(list1)

        Reply
    • Zeeshan says

      September 19, 2023 at 11:05 pm

      instead
      x = set(list1)
      print(x)

      Reply
      • Orens_10 says

        October 12, 2023 at 3:50 am

        I think we would simply do like this:
        print(list(set(list1)))

        Reply
    • Minh Vo Van says

      October 21, 2023 at 7:51 am

      list1 = [200 if x==20 else x for x in list1]
      print(list1)

      Reply
  23. 0xAH says

    March 24, 2023 at 11:34 pm

    #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)

    Reply
    • 0xAH says

      March 25, 2023 at 12:01 am

      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)

      Reply
    • NS says

      November 27, 2023 at 1:45 pm

      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)

      Reply
  24. sasuke says

    March 14, 2023 at 12:46 pm

    thank you

    Reply
  25. harshul Patel says

    December 15, 2022 at 12:55 pm

    # 1: Reverse a list in Python
    list1 = [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])

    Reply
    • harshul Patel says

      December 15, 2022 at 12:58 pm

      # 3: Turn every item of a list into its square
      numbers = [1, 2, 3, 4, 5, 6, 7]
      print([i*i for i in numbers])

      Reply
  26. Georgi Valkanov says

    November 13, 2022 at 3:36 am

    Exercise number 3

    numbers = [1, 2, 3, 4, 5, 6, 7]
    for index, item in enumerate(numbers):
    numbers[index] = item ** 2

    print(numbers)

    Reply
  27. Georgi Valkanov says

    November 13, 2022 at 2:33 am

    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)

    Reply
  28. vini1955 says

    October 13, 2022 at 2:36 am

    Exercise 2 – model solution adapted for 2 lists of different lengths

    def two_lists_index(list1, list2):
        list3 = [i + j for i, j in zip(list1, list2)]
        if len(list1) > len(list2):
            for n in range(len(list2), len(list1)):
                list3.append(list1[n])
        elif  len(list2) > len(list1):
            for n in range(len(list1), len(list2)):
                list3.append(list2[n])
        
        print(list3)
    
    two_lists_index(["M", "na", "i", "Ke"], ["y", "me", "s", "lly", "Ned", "Kelly"])
    Reply
    • vini1955 says

      October 13, 2022 at 2:38 am

      (please indent code as appropriate – tags don’t seem to work on my posts)

      Reply
  29. Hector says

    September 27, 2022 at 1:11 am

    I propose this solution based on a functional approach for exercise number three:

    numbers = [1, 2, 3, 4, 5, 6, 7]
    print(list(map(lambda x: x**2,numbers)))
    Reply
    • Richard says

      October 6, 2022 at 2:32 pm

      ‘list’ object is not callable

      Reply
  30. saikrishna says

    September 26, 2022 at 8:25 pm

    list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"]
    l1=[]
    l2=[]
    for i in list1:
      if len(i)==0:
        l1.append(i)
      else:
        l2.append(i)
    print(l2)
    Reply
    • arvind says

      March 10, 2023 at 10:12 pm

      you can just write like this :
      l1=[]
      for i in list1:
      if len(i)!=0:
      l1.append(i)

      print(l1)

      Reply
  31. saikrishna says

    September 26, 2022 at 8:24 pm

    Question:6

    list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"]
    l1=[]
    l2=[]
    for i in list1:
      if len(i)==0:
        l1.append(i)
      else:
        l2.append(i)
    print(l2)
    Reply
    • Ulvy says

      October 31, 2023 at 3:56 pm

      what if list1 has None value?

      Reply
  32. Rajak Shaik says

    September 20, 2022 at 12:08 pm

    list1[::-1]
    print(list1)
    Reply
  33. rohit singla says

    September 7, 2022 at 10:00 pm

    list1 = [100, 200, 300, 400, 500]
    list1[:-1]
    print(list1)
    Reply
  34. rohit singla says

    September 7, 2022 at 9:59 pm

    An alternate way of step 1:-

    list1 = [100, 200, 300, 400, 500]
    list1.reverse()
    print(list1)
    list1[:-1]
    print(list1)
    Reply
  35. Rinki says

    September 5, 2022 at 10:16 pm

    a = ["M", "na", "i", "Ke"]
    b = ["y", "me", "s", "lly"]
    c = [a[i]+b[i] for i in range(4)]
    print(c)
    Reply
  36. Newton Nandy says

    September 3, 2022 at 2:27 pm

    An alternate solution to Exercise 3.

    numbers = [1,2,3,4,5,6,7]
    numbers = []
    for value in range(1,8):
        
        numbers.append(value**2)
    print(numbers)
    Reply
  37. Vasim says

    August 10, 2022 at 12:52 am

    Thanks for this site

    Reply
  38. luke says

    August 7, 2022 at 12:50 pm

    exercise 1 in 3 different ways

    list1 = [100, 200, 300, 400, 500]
    #silution1
    for item in range(len(list1)-1,-1,-1):
        print(list1[item])
    #silution2
    for k in list1[::-1]:
        print(k)
    #silution3
    reversed_list = reversed(list1)
    for j in reversed_list:
        print(j)
    Reply
  39. yesmine says

    July 3, 2022 at 5:32 am

    exercise 6 :

    list1=["Mike","","Emma", "Kelly","","Brad"]
    while "" in list1:
        list1.remove("")
    print(list1)
    Reply
    • deus says

      September 2, 2022 at 11:33 pm

      list1 = ["M", "na", "i", "Ke"]
      list2 = ["y", "me", "s", "lly"]
      for i in range(4):
          print(i)
          listf=list1[i]+list2[i]
      print(listf)

      why this wrong?

      Reply
      • Akula Shafiulla says

        September 29, 2022 at 1:06 pm

        list1 = ["M", "na", "i", "Ke"]
        list2 = ["y", "me", "s", "lly"]
        listf=[]
        for i in range(4):
            listf.append(list1[i]+list2[i])
        print(listf)
        Reply
      • geethika says

        July 17, 2023 at 10:54 am

        list1 = ["M", "na", "i", "Ke"]
        list2 = ["y", "me", "s", "lly"]
        listf = []

        for i in range(4):
        listf.append(list1[i] + list2[i])

        print(listf)

        Reply
  40. yesmine says

    June 30, 2022 at 6:36 am

    exercise 3

    numbers = [1, 2, 3, 4, 5, 6, 7]
    power=[' ']* len(numbers)
    for i in range (len(numbers)) :
        power[i] = numbers[i] ** 2
    print(power)
    Reply
    • Nitesh Paudel says

      August 23, 2022 at 6:11 pm

      why make it hard
      just do

      output = [x*x for x in numbers]

      Reply
  41. abhay says

    June 27, 2022 at 5:46 pm

    #for using for loop
    list1 = [5, 20, 15, 20, 25, 50, 20]
    a= []
    for i in list1:
        if i ==20:
            continue
        a.append(i)
    print(a)
    Reply
    • abhay says

      June 27, 2022 at 5:47 pm

      its q. 10

      Reply
  42. abhay says

    June 27, 2022 at 5:23 pm

    #for q 4
    list1 = ["Hello ", "take "]
    list2 = ["Dear", "Sir"]
    b= []
    for i in list1:
        for j in list2:
            a = i+j
            b.append(a)
    print(b)
    Reply
  43. EniG says

    June 7, 2022 at 6:16 pm

    Question 3

    list1 = [ 1 , 2 , 3 ,4 ,6]
    currentNum =[]
    
    for x in list1:
        currentNum = x * x
    
        print(currentNum , end= " ")

    As a begginer I tried this and it worked also

    Reply
    • Kholtemirov Abdulmalik says

      August 10, 2022 at 11:10 pm

      Sorry bro, but your code does not work.
      I changed it to the correct version
      Here is it:

      list1 = [1, 2, 3, 4, 5, 6]
      currentNum = []
      for x in list1:
          currentNum.append(x * x)
      print(currentNum, end=" ")
      Reply
  44. Mike says

    June 6, 2022 at 2:29 pm

    ex 10

    list1 = [5, 20, 15, 20, 25, 50, 20]
    for ch in list1:
        if ch == 20:
            list1.pop(list1.index(ch))
    print(list1)
    Reply
  45. abdou says

    June 6, 2022 at 2:59 am

    Exercise 5:

    list1 = [10, 20, 30, 40]
    list2 = [100, 200, 300, 400]
    for x,y in zip(list1 , reversed(list2)):
        print(f'{x} {y}')
    Reply
  46. Rishikesh Shah says

    March 30, 2022 at 4:24 pm

     list1 = [5, 10, 15, 20, 25, 50, 20]
    
    for elem in list1:
        # search for duplicate item
        if list1.count(elem) >1:        
            get_index_duplicate = list1.index(elem)
    
    new_list = list1[:get_index_duplicate] + [200] + list1[get_index_duplicate + 1:]
    print(new_list) 
    Reply
  47. Rishikesh Shah says

    March 30, 2022 at 10:06 am

    Exercise 4:

    list1 = ["Hello", "take"]
    list2 = ["Dear", "Sir"]
    res_list = []
    for i in range(len(list1)):
        for j in range(len(list2)):
            res_list.append(list1[i]+ " " + list2[j])
    
    print(res_list)
    Reply
  48. yuvraj jadhav says

    March 27, 2022 at 4:53 pm

    exercise 10:

    l1 = [5, 20, 15, 20, 25, 50, 20]
    
    for i in l1:
        if l1.count(20)>1:
            l1.remove(20)
    l1.remove(20)
    print(l1)
    Reply
  49. Rohit Chandoriya says

    March 21, 2022 at 4:40 pm

    Question 6 with list comprehension

    
    import string
    #num1=input("Enter the starting number: ")
    #num2=input("Enter the starting number: ")
    num1=[10,20,30,40,'']
    num12=[100,200,300,400,'']
    
    def replace(a):
        res=[x for x in a if x!='']
        print(res)
    
    
    print(replace(num1))
    Reply
  50. Rohit Chandoriya says

    March 21, 2022 at 4:10 pm

    For Question 3 using list comprehension

    
    import string
    #num1=input("Enter the starting number: ")
    #num2=input("Enter the starting number: ")
    num1=[1,2,300,4,5,67,8,81,89,9,100]
    #num12=[1,2,300,'manenge',4,5,67,8,81,89,9,100,'ba',]
    
    def replace(a):
        list3=[i**2 for i in a]
        print(list3)
    
    print(replace(num1))
    Reply
  51. ABD RRAHIM says

    February 25, 2022 at 11:23 pm

    Thanks, it was a simple and useful exercise 😄️💜️

    Reply
  52. Hutchington says

    February 19, 2022 at 11:34 pm

    Hello, For Q3: Turning every item of a list into its square,

    numbers = [1,2,3,4,5,6,7]
    square = [pow(i, 2) for i in numbers]
    print(square)
    Reply
  53. Danilo says

    January 15, 2022 at 6:39 pm

    Q6

    
    l1 = ["Mike", "", "Emma", "Kelly", "", "Brad"]
    for i in l1:
        if not i:
            l1.remove(i)
    print(l1)
    Reply
    • DJ says

      November 2, 2022 at 4:43 pm

      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)

      Reply
  54. Danilo says

    January 15, 2022 at 2:09 pm

    Question 2

    
    l1 = ["M", "na", "i", "Ke"]
    l2 = ["y", "me", "s", "lly"]
    l3 = []
    
    a = len(l1)
    b = len(l2)
    
    c = a if a < b else b
    
    for i in range(c):
        x = l1[i] + l2[i]
        l3.append(x)
    
    print(l3)
    Reply
    • mukesh says

      April 15, 2022 at 10:30 pm

      if l2 length is more then extra element is not added in list

      Reply
      • leela arvind says

        May 4, 2022 at 9:25 am

        yes try this one

        list1 = ["M", "na", "i", "Ke","hhihi"]
        list2 = ["y", "me", "s"]
        res=[]
        
        i=0
        k=len(list1)
        l=len(list2)
        n=min(k,l)
        for x in list1:
            if i<n:
             z=x+list2[i]
             i+=1
             res.append(z)
        s=list1[i:]+list2[i:]
        res.extend(s)
        print(res)
        Reply
    • pavan says

      September 23, 2022 at 11:38 am

      list1 = ["M", "na", "i", "Ke"]
      list2 = ["y", "me", "s", "lly"]
      
      list_a=[]
      for i in range(len(list1)):
          add=list1[i]+list2[i]
          
          list_a.append(add)
      print(list_a)
      Reply
  55. Bhavesh says

    January 3, 2022 at 2:06 am

    list1 = [5, 20, 15, 20, 25, 50, 20]
    print(list(filter(lambda x: x!=20,list1)))
    Reply
    • Hutchington says

      February 19, 2022 at 11:25 pm

      This is a good one.

      Reply
    • Shovon says

      March 29, 2022 at 9:15 pm

      list1 = [5, 20, 15, 20, 25, 50, 20]
      empty=[]
      for i in list1:
          if i!=20:
              empty.append(i)
      print(empty)
      Reply
    • Nandyala Chiranjeevudu says

      July 20, 2022 at 10:16 pm

      list1 = [5, 20, 15, 20, 25, 50, 20]
      for i in list1:
        if i!=20:
          print(i)
      Reply
  56. Giorgos says

    December 23, 2021 at 12:54 am

    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?

    numbers = [1, 2, 3, 4, 5, 6, 7]
    
    for i in numbers:
        numbers[numbers.index(i)] = i * i
    
    
    print(numbers)
    Reply
    • Katerina says

      June 29, 2022 at 5:43 pm

      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:

      numbers = [1, 2, 3, 4, 5, 6, 7]
      for i in numbers:
          print("i = ", i)
          numbers[numbers.index(i)] = i * i
          print("current list = ", numbers)
      print(numbers)

      you get the following:

      i =  1
      current list =  [1, 2, 3, 4, 5, 6, 7]
      i =  2
      current list =  [1, 4, 3, 4, 5, 6, 7]
      i =  3
      current list =  [1, 4, 9, 4, 5, 6, 7]
      i =  4
      current list =  [1, 16, 9, 4, 5, 6, 7]
      i =  5
      current list =  [1, 16, 9, 4, 25, 6, 7]
      i =  6
      current list =  [1, 16, 9, 4, 25, 36, 7]
      i =  7
      current list =  [1, 16, 9, 4, 25, 36, 49]

      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.

      Reply
  57. shaikh sameer says

    December 18, 2021 at 12:06 pm

    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:

    numbers = [1, 2, 3, 4, 5, 6, 7]
    
    *solution: 
    list1= [1, 2, 3, 4, 5, 6, 7]
    list2=[num**2 for num in (list1)]
    print(list2)
    Reply
    • Serkan says

      July 11, 2022 at 6:30 pm

      numbers = [1, 2, 3, 4, 5, 6, 7]
      c = lambda y: list(map(lambda x: x ** 2, y))
      print(c(numbers))
      Reply
  58. Danilo says

    December 15, 2021 at 6:10 pm

    Question 10

    list1 = [5, 20, 15, 20, 25, 50, 20]
    for i in list1:
        if i == 20:
            list1.remove(i)
    print(list1)
    Reply
    • Ameer says

      January 13, 2022 at 2:51 pm

      list1 = [5, 20, 15, 20, 25, 50, 20]
      ans = [i for i in list1 if i!=20]
      print(ans)

      One simplest method.

      Reply
  59. Danilo says

    December 15, 2021 at 5:55 pm

    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.

    
    l1 = [5, 10, 15, 20, 25, 50, 20]
    for i in range(int(len(l1) - 1)):
        if l1[i] == 20:  # If item found
            l1[i] = 200  # Update item
            break         # Stop iteration to stop it from updating any further item's occurrence
    print(l1)

    Sorry I couldn’t find a way to use the index() function which is the aim of this exercise

    Reply
    • Vasanth V says

      February 16, 2022 at 7:50 pm

      Instead of range() you could use enumerate, to avoid finding the length of the list and an arithmetic operation. Like below,

      
      for index, l1 in enumerate(list1):
          if l1 == 20:  # If item found
              list1[index] = 200  # Update item
              break         # Stop iteration to stop it from updating any further item's occurrence
      
      print list1

      Correct me if am wrong

      Reply
  60. Danilo says

    December 15, 2021 at 3:37 pm

    Question 1

    
    list1 = [100, 200, 300, 400, 500]
    list2 = []
    for i in range(int(len(list1)) - 1, -1, -1):
        list2.append(list1[i])
    print(list2)
    Reply
  61. Majid says

    December 9, 2021 at 10:23 am

    voooowww! Your articles and exercises are helpful. Thanks alot.

    Reply
  62. rphpdeveloper says

    December 8, 2021 at 4:27 pm

    Thank you for the great contents, i have learn a lot.
    for problem 10, can we do this:

    list1 = [5, 20, 15, 20, 25, 50, 20]
    list2 = list(filter(lambda x: x !=20, list1))
    print(list2)
    Reply
  63. Pratik Singh says

    November 30, 2021 at 9:01 am

    list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]

    How to get the output from this list as below :

    ['a','b','c','d'......till 'n']
    Reply
  64. Jenna Smiles says

    October 30, 2021 at 6:10 am

    Hey just wanted to say thanks! These are very helpful for newbies like me 🙂

    Reply
    • Vishal says

      November 14, 2021 at 11:15 am

      I am glad it helped you, Jenna.

      Reply
      • ajibola says

        February 9, 2022 at 1:52 am

        how can I have your contact

        Reply
  65. sama71 says

    October 26, 2021 at 9:50 pm

    Q10

    list1 = [5, 20, 15, 20, 25, 50, 20]
    count = list1.count(20)
    for i in range(count):
        list1.remove(20)
    print(list1)
    Reply
    • dodke sushobhan says

      December 5, 2021 at 9:23 pm

      list1 = [5, 20, 15, 20, 25, 50, 20]
      
          for i in list1:
      
              if i == 20:
                  list1.remove(i)
          print(list1)
      Reply
  66. Anne Deborah says

    October 22, 2021 at 4:01 am

    FOR EXERCISE 8, another different(not so different) approach:

    list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]
    subList=["h","i","j"]
    
    for i in range(len(subList)):
        list1[2][1][2].append(subList[i])
    print (list1)
    Reply
  67. Anne Deborah says

    October 22, 2021 at 3:57 am

    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.

    list1=["Hello","take"]
    list2=["Dear","Care"]
    newList=[] 
    
    for i in list1:
         for j in list2:
             newList.append(i+' '+j)
    print(newList)
    Reply
  68. Anne Deborah says

    October 22, 2021 at 3:47 am

    Another approach for exercise2:

    aList=[1,2,3,4,5,6,7]
     newList=[]
    
     for i in range(len(aList)):
         newList.append(aList[i]**2)
     print(newList)
    Reply
    • Anne Deborah says

      October 22, 2021 at 3:49 am

      exercise3*** .My bad!

      Reply
  69. Anne Deborah says

    October 22, 2021 at 3:45 am

    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

    aList=[100,200,300,400,500]
    newList=[]
     x=len(aList)-1
    
    while x>=0: 
         newList.append(aList[x])
         x=x-1
     print(newList)
    Reply
  70. Kareman says

    October 18, 2021 at 8:40 pm

    exercise6:

    list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"]
    list2 = []
    for i in list1:
        if i:
            list2.append(i)
    print(list2)
    Reply
  71. Thanawat Launakorn says

    September 28, 2021 at 11:06 pm

    ex 10

    list1 = [5, 20, 15, 20, 25, 50, 20]
    answer = [i for i in list1 if i != 20] 
    print(answer)
    Reply
    • Sante Allegrini says

      October 3, 2021 at 9:57 pm

      Is this right for ex 10?

      list1 = [5, 20, 15, 20, 25, 50, 20]
      list1 = [x for x in list1 if x != 20]
      print(list1)
      Reply
  72. Leonardo Wolo says

    July 31, 2021 at 5:52 pm

    For exercise 5, it is also possible to do it this way:

    list1 = [10, 20, 30, 40]
    list2 = [100, 200, 300, 400]
    
    for i in range(len(list1)):
        print(list1[i], list2[len(list2)-(1+i)])
    Reply
    • Vishal says

      August 2, 2021 at 10:22 am

      Thank you for the alternative solution, Leonardo.

      Reply
  73. Chethan Krishna says

    July 29, 2021 at 4:51 pm

    For 10

    list1 = [5, 20, 15, 20, 25, 50, 20]
    for i in list1:
        if i == 20:
            list1.remove(i)
    print(list1)
    Reply
    • venkat says

      August 31, 2021 at 5:26 pm

      another way:

      print(list(filter(lambda x: x != 20, list1)
      Reply
  74. Chethan Krishna says

    July 29, 2021 at 4:25 pm

    For Exercise 6 :

    list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"]
    for i in list1:
        if i == '':
            list1.remove(i)
    print(list1)
    Reply
  75. Mike says

    July 22, 2021 at 12:46 am

    For Ex:5 I am not using the Zip function as I have not learned it yet. It a long way, but works

    def main():
        list1 = [10,20,30,40,50,60,70]
        list2 = [100,200,300,400,500,600,700]
        cnt = -1
        for i in range(len(list1)):
            print(list1[i],list2[cnt])
            cnt = cnt - 1
    
    main()
    Reply
  76. Pallavi says

    July 6, 2021 at 10:40 am

    Hi,
    for Ex3:
    How do I modify this code to get the right o/p?

    
    list1 = [1, 2, 3, 4, 5, 6, 7]
    sq=[]
    for i in range(len(list1)):
         list1[i]*list1[i]
         sq.append(list1[i])
    print(sq)
    Reply
    • Shubham says

      July 11, 2021 at 11:44 am

      list1 = [1, 2, 3, 4, 5, 6, 7]
      sq=[]
      for i in range(len(list1)):
           square=list1[i]*list1[i]
           sq.append(square)
      print(sq)
      Reply
      • kemil says

        August 18, 2021 at 8:00 pm

        aList = [1, 2, 3, 4, 5, 6, 7]
        l = []
        for i in aList:
        	l.append(i*i)
        print(l)
        Reply
    • Shubham says

      June 19, 2022 at 11:16 am

      for i in list1:  
             sq.append(i*i)
      print(sq)
      Reply
  77. Hinata says

    July 5, 2021 at 8:04 pm

    problem = 3

    
    aList = [1, 2, 3, 4, 5, 6, 7] 
    p = []
    for i in range(len(aList)):
        p.append(aList[i]**2)
    print(p)
    
    print("From Hinata Uzamaki")
    Reply
  78. Pallavi says

    July 5, 2021 at 10:10 am

    Hi,
    For Ex:2:
    this following code id giving me right output. But can somebody tell me the best practice please..

    
    list1 = ["M", "na", "i", "Ke"]
    list2 = ["y", "me", "s", "lly"]
    for i in list1:
        list3=list1[0]+list2[0]
    for i in list1:
         list4=list1[1]+list2[1]
    for i in list1:
        list5=list1[2]+list2[2]
    for i in list1:
        list6=list1[3]+list2[3]
    print([list3,list4,list5,list6])
    Reply
    • Khadim Hussain says

      July 5, 2021 at 11:52 am

      list3 = []
      for i in range(len(list1)):
            list3.append(list1[i] + list2[i])
      list3
      Reply
    • Hinata says

      July 5, 2021 at 7:41 pm

      
      p = []
      for i in range(len(list1)):
          for j in range(len(list2)):
              if(i==j):
                  p.append(list1[i]+list2[j])
      print(p)
      Reply
      • Pallavi says

        July 6, 2021 at 12:21 am

        Thanks Hinata 🙂

        Reply
    • Pallavi says

      July 6, 2021 at 12:14 am

      Thanks khadim. I understood my fault now 🙂

      Reply
    • Shivam says

      August 12, 2021 at 7:39 pm

      list3 = [i+j for i,j in zip(list1,list2)
      list3
      Reply
    • Naruto Uzumaki says

      September 28, 2021 at 2:16 pm

      # list1 = ["M", "na", "i", "Ke"]
      # list2 = ["y", "me", "s", "lly"]
      # print(list(i+j for i,j in zip(list1,list2)))

      From Naruto Uzumaki

      Reply
      • baruto says

        March 14, 2023 at 12:45 pm

        thank you

        Reply
    • Nagraj says

      September 28, 2021 at 10:07 pm

      do one thing

      Reply
  79. AndyLeeParker says

    June 30, 2021 at 3:19 am

    Anybody else has trouble not doing things the hard way? Here’s my solution for problem 4. Yours was so much simpler!

    from itertools import product
    # list1 = ["Hello ", "take "]
    # list2 = ["Dear", "Sir"]
    # res = ['%s %s' % (ele[0], ele[1]) for ele in product(list1, list2)] 
    # print( str(res))
    Reply
  80. Daniel Tobon says

    April 21, 2021 at 7:18 pm

    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)
    
    Reply
    • saad says

      June 2, 2021 at 9:53 pm

      hey dude! how to generate this program??
      “Program to generate the sequence: -5,10, -15,20, -25 ——up to n terms”

      Reply
      • Darshan G says

        June 3, 2021 at 7:09 pm

        n = int(input("enter a number "))
        for i in range(5, n+1 ,5):
            if i % 2 == 1:
                print(-i, end =" ")
            else:
                print(i, end =" ")

        try this

        Reply
        • saad says

          June 4, 2021 at 11:04 am

          it won’t give the required list:
          enter a number25
          5 -5 -15 -25 25
          this is how it gives result

          Reply
          • saad says

            June 4, 2021 at 1:13 pm

            ok thanks

          • sheryar says

            December 5, 2021 at 5:11 pm

            n = int(input("enter a number "))
            for i in range(5, (n*5)+1 ,5):
                if i % 2 == 1:
                    
                    print(-i, end =" ")
                else:
                    print(i, end =" ")
        • Sagar Bhatia says

          June 5, 2021 at 7:23 pm

          n = int(input("enter a number "))
          for i in range(5, 5*n ,5):
              if i % 2 == 1:
                  
                  print(-i, end =" ")
              else:
                  
                  print(i, end =" ")
          Reply
        • JK says

          June 19, 2021 at 8:48 pm

          def generate(n):
              j = True
              for i in range(1, n+1):
                  if j:
                      print(-5 * i)
                      j = not j
                  else:
                      print(5 * i)
                      j = not j
          
          
          generate(20)
          Reply
      • Tushar Singh says

        June 15, 2021 at 12:23 am

        n = int(input('Enter a number '))
        for i in range(1,n+1):
            if i%2 !=0:
                print(-5*i, end = ' ')
            else:
                print(5*i, end = ' ')
        Reply
    • Suraj says

      June 29, 2021 at 11:43 am

      list1 = [5, 20, 15, 20, 25, 50, 20]
      c = list1.count(20)
      for i in range(c):
          list1.remove(20)
      print(list1)

      hows mine?

      Reply
    • Hinata Uzamaki says

      July 5, 2021 at 7:55 pm

      
      list1 = [5, 20, 15, 20, 25, 50, 20]
      
      p = []
      for i in range(len(list1)):
          if(list1[i]==20):
              continue
          p.append(list1[i])
      print(p)
      Reply
    • Raja Chowdary Polepalli says

      July 21, 2021 at 11:56 am

      Here is my solution in two methods:

      method-1:

      list1 = [5, 20, 15, 20, 25, 50, 20]
      for i in range(3):
          list1.remove(20)
      print(list1)

      method-2:

      list1 = [5, 20, 15, 20, 25, 50, 20]
      list2=[i for i in list1 if i !=20]
      print(list2)
      Reply
  81. Siddhartha Roy says

    April 7, 2021 at 4:55 am

    Exercise 10: Given a Python list, remove all occurrence of 20 from the list

    list1 = [5, 20, 15, 20, 25, 50, 20]
    for i in list1:
        if i == 20:
            list1.remove(20)
    print(list1)

    Result: [5, 15, 25, 50]

    Reply
    • Nonso says

      June 2, 2021 at 7:16 pm

      if you have multiple 20s , there will be a logic error

      Reply
      • mike says

        July 22, 2021 at 8:59 pm

        I don’t get a logic error

        Code:

        list1 = [20, 5, 20, 15, 20, 25, 50, 20, 20, 20,21, 22, 23]
            for num in list1:
                if num == 20:
                    list1.remove(20)
            print(list1)

        Output:

        [5, 15, 25, 50, 20, 21, 22, 23] 
        Reply
  82. rocky says

    April 1, 2021 at 3:45 pm

    def removeValue(sampleList, val):
       return [value for value in sampleList if value != val]
    
    resList = removeValue(list1, 20)
    print(resList)
    Reply
  83. Aakanksha Jagyasi says

    December 25, 2020 at 6:30 pm

    please tell how we decide dimension as in ques 8 list[2][1][2]

    Reply
    • Pavan says

      June 2, 2021 at 7:06 am

      You just have to count the number of items in each nested list.
      
      Reply
    • sadhana says

      July 28, 2021 at 5:24 pm

      Index value for question 8:

      A index value is [0]
      B index value is[1]
      [C,L] index value is[2]
      C index value is[2][0]
      [D,K] index value is[2][1]
      D index value is[2][1][0]
      E index value is[2][1][1]
      [F,G] index value is [2][1][2]
      F index value is[2][1][2][0]
      G index value is[2][1][2][1]
      K index value is[2][1][3]
      L index value is[2][2]
      M index value is[3]
      N index value is[4]

      I hope this might help u

      Reply
  84. Kumar says

    November 25, 2020 at 6:03 pm

    Problem 1:

    aList = [100, 200, 300, 400, 500]
    aList = aList[::-1]
    print(aList)

    Other Approach:- The Below also works

    aList = [100, 200, 300, 400, 500]
    aLsit.reverse()
    print(aList)
    Reply
  85. Arpit says

    November 13, 2020 at 12:01 pm

    Another solution for Q6

    list1 = [“Mike”, “”, “Emma”, “Kelly”, “”, “Brad”]
    print([item for item in list1 if len(item)>0] )
    Reply
  86. Mohammed Hisham Mohammed says

    October 27, 2020 at 8:55 pm

    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?

    def removeNegatives(listOfIntegers):
    
        for item in listOfIntegers:
            if item < 0: 
                listOfIntegers[listOfIntegers.index(item)] = -item
    
        print (listOfIntegers)
    Reply
    • Milu says

      September 27, 2021 at 4:01 am

      you have to add at the end of your def a return statement:

      return listOfIntegers

      Reply
  87. isMeStranger says

    October 15, 2020 at 4:28 pm

    Alternative answer for Q10:

     list1 = [5, 20, 15, 20, 25, 50, 20]
               for x in list1:
                      if x == 20:
                           list1.remove(20)
               print(list1)
    Reply
  88. isMeStranger says

    October 15, 2020 at 4:27 pm

    Alternative answer for Q10:

    list1 = [5, 20, 15, 20, 25, 50, 20]
    for x in list1:
      if x == 20:
        list1.remove(20)
    print(list1)
    Reply
    • Paweł says

      November 12, 2020 at 12:44 am

      One another:

      list1 = [5, 20, 15, 20, 25, 50, 20]
      z = list(filter(lambda x: x!=20, list1))
      print(z)
      Reply
    • Kita says

      November 24, 2020 at 8:40 am

      Here’s another

      
       list1 = [5, 10, 15, 20, 25, 50, 20]
       while 20 in list1:
           list1.remove(20)
       print(list1)
      
      Reply
  89. bhavya says

    August 21, 2020 at 11:01 am

    Can anyone please point out the mistake, or is this code correct…..

    list1 = [5, 10, 15, 20, 25, 50, 20]
    if 20 in list1:
         list1.remove(20)
         list1.insert(3, 200)
    
    print(list1)
    Reply
    • mohmmad says

      September 5, 2020 at 6:09 pm

      you must loop over the remove function in order to work

      Reply
    • mohmmad says

      September 5, 2020 at 6:11 pm

      list1 = [5, 10, 15, 20, 25, 50, 20]
      for x in list1:
          if 20 in list1:
              list1.remove(20)
      list1.insert(3,200)
      print(list1)
      Reply
    • Charan says

      October 1, 2020 at 7:57 pm

      your program is correct.it is running without any error

      Reply
    • Adish Jain says

      October 4, 2020 at 4:05 pm

      [5,10,15,300,25,50,20]

      Reply
  90. sheena says

    August 18, 2020 at 1:41 pm

    list12 = [5, 20, 15, 20, 25, 50, 20]
    for i in list12:
        if(i==20):
            list12.remove(i)
    print(list12)
    
    		
    Reply
  91. Deepak Sen says

    August 12, 2020 at 11:24 am

    Any alternative ans for Q-2

    Reply
    • sheena says

      August 18, 2020 at 1:43 pm

      list1 = ["M", "na", "i", "Ke"]
      list2 = ["y", "me", "s", "lly"]
      newlist=list((zip(list1, list2)))
      aa=[]
      for i in newlist:
          aa.append(''.join(i))
      print(aa)
      
      		
      Reply
    • priyanka gade says

      June 11, 2021 at 10:21 pm

      list1 = ["M", "na", "i", "Ke"]
      list2 = ["y", "me", "s", "lly"]
      z1=zip(list1,list2)
      for i,j in z1:
          sum=i+j
          print(sum)
      Reply
  92. Naveen Kumar says

    July 19, 2020 at 11:11 am

    question no.10

    list1 = [5, 20, 15, 20, 25, 50, 20]
    k=len(list1)
    k=list1.count(20)
    for i in range(k):
        list1.remove(20)
    print(list1)
    Reply
    • Ravneet says

      July 23, 2020 at 9:18 pm

      Thanks..it really helps:-)

      Reply
    • nandish says

      July 25, 2020 at 12:12 pm

      list1 = [5, 20, 15, 20, 25, 50, 20]
      list2=list(set(list1))
      list2.remove(20)
      print(list2)
      Reply
  93. sankar nath says

    July 17, 2020 at 7:52 pm

    Questions 4:

    
    list1 = ["Hello", "Take"]
    list2 = ["Dear", "sir"]
    
    print( list1[0]+ " "+list2[0], list1[0]+ " "+ list2[1], list1[1]+" "+list2[0], list1[1]+list2[1] )
    Reply
    • priyanka gade says

      June 11, 2021 at 10:23 pm

      list1 = ["Hello ", "take "]
      list2 = ["Dear", "Sir"]
      list3=[i+j for i in list1 for j in list2]
      print(list3)
      Reply
  94. bharanisampath says

    July 16, 2020 at 12:20 pm

    Any alternate answers for Q-10

    Reply
    • Naveen Kumar says

      July 19, 2020 at 11:09 am

      Here is an alternate solution for question no.10

      list1 = [5, 20, 15, 20, 25, 50, 20]
      k=len(list1)
      k=list1.count(20)
      for i in range(k):
          list1.remove(20)
      print(list1)
      Reply
      • Hi says

        November 21, 2020 at 3:15 pm

        list1 = [5, 20, 15, 20, 25, 50, 20]
        for x in list1:
            if x ==20:
                list1.remove(20)
        print(list1)
        Reply
    • nandish says

      July 25, 2020 at 12:16 pm

      list1 = [5, 20, 15, 20, 25, 50, 20]
      list2=list(set(list1))
      list2.remove(20)
      print(list2)
      Reply
    • Adarsh Anand says

      November 8, 2020 at 11:43 am

      
      list1 = [5, 20, 15, 20, 25, 50, 20]
      
      for item in list1:
          if item == 20:
              c = list1.index(item)
              list1.pop(c)
      
      print(list1)
      
      Reply
  95. Alec Nigh says

    June 24, 2020 at 12:08 am

    Alternative answer to Q9 — Note: would have convert back to a list to satisfy the question requirements.

    
    list1 = [5, 10, 15, 20, 25, 50, 20]
    list1 = " ".join(map(str,list1))
    list2 = list1.replace("20", "200", 1)
    print(list2)
    
    Reply
  96. Qadeer Rizvi says

    June 23, 2020 at 3:33 am

    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.

    Reply
    • Vishal says

      June 25, 2020 at 3:08 pm

      You’re welcome, Qadeer Rizvi.

      Reply
  97. Bostan Khan says

    June 14, 2020 at 7:38 pm

    sir your article are amazing very helpful for me.keep it up and live long

    Reply
    • Vishal says

      June 15, 2020 at 5:01 pm

      Thank you, Bostan Khan, for your kind words

      Reply
  98. shubham kumar singh says

    June 13, 2020 at 1:07 pm

    list1[2][1][2].extend(subList)
    i can’t understand the indexing value.please heip me out.

    Reply
    • shivam pal says

      June 17, 2020 at 11:08 am

      list1[2][1][2].extend(["h", "i", "j"])
      Reply
    • Paweł says

      November 12, 2020 at 12:43 am

      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.

      Reply
  99. Monika Gupta says

    June 11, 2020 at 11:13 am

    can you explain Q4 flow of code not able to understand

    Reply
    • Bostan Khan says

      June 14, 2020 at 7:33 pm

      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

      Reply
    • priyanka gade says

      June 11, 2021 at 10:24 pm

      list1 = ["Hello ", "take "]
      list2 = ["Dear", "Sir"]
      list3=[i+j for i in list1 for j in list2]
      print(list3)
      Reply
  100. Prashanth says

    May 29, 2020 at 8:14 pm

    Good Work Vishal !! Do you run any online classes for Python. I am ready to join in your class

    Reply
    • Vishal says

      May 31, 2020 at 11:13 am

      Hey Prashanth, I am not running any classes as of now. I will definitely let you know once I started it.

      Reply
  101. Alec Nigh says

    May 29, 2020 at 12:02 am

    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!

    Reply
  102. Marcin says

    May 26, 2020 at 9:49 pm

    Question 7

    list1[2][2].append(7000)

    Question 8

            
    list1[2][1][2].extend(subList)

    I don’t understand the index of lists. Where they come from? Does someone want to explain?

    Reply
    • Bostan Khan says

      June 14, 2020 at 7:36 pm

      its like array indexing access ,the point here to be noted each list in the list will be consider an element of the list

      Reply
    • Dalvir says

      July 31, 2020 at 4:29 pm

      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.

      Reply
    • Aditya Patel says

      March 4, 2022 at 9:06 am

      list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]
      index [0] = 10
      index [1] = 20
      index [2] = [300,400,[5000,6000],500]
      index [3] = 30
      index [4] = 40
      Reply
  103. Gayathri says

    May 16, 2020 at 3:49 pm

    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

    Reply
    • Ashish says

      July 24, 2020 at 7:22 am

      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.

      Reply
  104. Shahnawaz says

    May 8, 2020 at 4:12 pm

    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])
    
    Reply
    • shivam pal says

      June 17, 2020 at 11:13 am

      
      for i in list1,list2[::-1]:
        print(i)
      
      Reply
  105. Noma says

    May 1, 2020 at 5:24 am

    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 ?

    Reply
    • Vishal says

      May 4, 2020 at 9:56 am

      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)
      Reply
    • Yashu gaur says

      August 1, 2020 at 1:33 pm

      Thanks sir it gave a lot of help to me. Thanks again

      Reply
  106. Pallavi says

    April 15, 2020 at 5:38 pm

    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

    Reply
    • Vishal says

      April 15, 2020 at 9:25 pm

      Thank you, Pallavi. Within two weeks you will see new topics for beginners on PYnative

      Reply
      • suryanshu says

        December 18, 2021 at 7:11 pm

        Please tell me the difference between lists and tuples.

        Reply
        • sithija says

          October 16, 2022 at 7:33 pm

          lists are mutable whereas tuples are immutable.

          Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Basics Python Exercises
TweetF  sharein  shareP  Pin

  Python Exercises

  • All Python Exercises
  • Basic Exercises for Beginners
  • Loop Exercises
  • Intermediate Python Exercises
  • Input and Output Exercises
  • Functions Exercises
  • String Exercises
  • List Exercises
  • Dictionary Exercises
  • Set Exercises
  • Tuple Exercises
  • Data Structure Exercises
  • Comprehensions Exercises
  • Collections Module Exercises
  • Date and Time Exercises
  • OOP Exercises
  • Exception Handling Exercises
  • Math and Statistics Exercises
  • File Handling Exercises
  • OS and Sys Module Exercises
  • Regex Exercises
  • Lambda & Functional Programming Exercises
  • Iterators & Generators Exercises
  • Itertools & Functools Exercises
  • Random Data Generation Exercises
  • NumPy Exercises
  • Pandas Exercises
  • Matplotlib Exercises
  • Python Database Exercises
  • Python JSON Exercises

 Explore Python

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

All Python Topics

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

About PYnative

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

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

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

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

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

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com

深圳市网捷达科技有限公司 联系电话:18910898173;

ICP备案号:粤ICP备2024312167号-2

Copyright © 网捷达 版权所有