Learn with Yasir

Share Your Feedback

Find and Fix Mistakes in Python Lists – Practice Debugging Exercises

Boost your Python skills by identifying and correcting common mistakes in list operations. Practice debugging Python list syntax, indexing errors, and method misuse with hands-on examples.

Topic: lists


🧪 Fix & Find Questions

🟢 Beginner Fix & Find

  1. Fix the list creation error:

    fruits = ['apple', 'banana', 'orange']
    print(fruits[3])
    

    Hint: 💡 Remember how list indexing works in Python.

    🔍 View Issue & Fixed Solution

    Issue: Trying to access an index that's out of range.

    ✅ Fixed Solution

    fruits = ['apple', 'banana', 'orange']
    print(fruits[2])  # Last element is at index 2 (0-based indexing)
    

  2. Fix the list element removal:

    colors = ['red', 'green', 'blue']
    colors.remove('yellow')
    print(colors)
    

    Hint: 💡 What happens when removing a non-existent element?

    🔍 View Issue & Fixed Solution

    Issue: Trying to remove an element that doesn't exist in the list.

    ✅ Fixed Solution

    colors = ['red', 'green', 'blue']
    if 'yellow' in colors:
        colors.remove('yellow')
    print(colors)  # Now won't raise ValueError
    

🟡 Intermediate Fix & Find

  1. Fix the list slicing operation:

    numbers = [0, 1, 2, 3, 4, 5]
    middle = numbers[2:4]
    print(middle[-1])  # Should print 4
    

    Hint: 💡 Check the slice end index and negative indexing.

    🔍 View Issue & Fixed Solution

    Issue: The slice doesn't include the desired last element.

    ✅ Fixed Solution

    numbers = [0, 1, 2, 3, 4, 5]
    middle = numbers[2:5]  # or numbers[2:]
    print(middle[-1])  # Now correctly prints 4
    

  2. Fix the list method usage:

    items = [1, 2, 3]
    items.append([4, 5])
    print(items)  # Should show [1, 2, 3, 4, 5]
    

    Hint: 💡 Check the difference between append() and extend().

    🔍 View Issue & Fixed Solution

    Issue: append() adds the entire list as a single element.

    ✅ Fixed Solution

    items = [1, 2, 3]
    items.extend([4, 5])  # or items += [4, 5]
    print(items)  # Now correctly shows [1, 2, 3, 4, 5]
    

🔴 Advanced Fix & Find

  1. Fix the list reverse operation:

    values = [10, 20, 30, 40]
    reversed_values = values.reverse()
    print(reversed_values)  # Should print [40, 30, 20, 10]
    

    Hint: 💡 Remember that some list methods modify in-place and return None.

    🔍 View Issue & Fixed Solution

    Issue: reverse() modifies the list in-place and returns None.

    ✅ Fixed Solution

    # Solution 1: Use the method then print the original
    values = [10, 20, 30, 40]
    values.reverse()
    print(values)
    
    # Solution 2: Use slicing to create a reversed copy
    values = [10, 20, 30, 40]
    reversed_values = values[::-1]
    print(reversed_values)
    

📚 Related Resources