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 the list creation error:
fruits = ['apple', 'banana', 'orange']
print(fruits[3])
Hint: 💡 Remember how list indexing works in Python.
Issue: Trying to access an index that's out of range.
fruits = ['apple', 'banana', 'orange']
print(fruits[2]) # Last element is at index 2 (0-based indexing)
Fix the list element removal:
colors = ['red', 'green', 'blue']
colors.remove('yellow')
print(colors)
Hint: 💡 What happens when removing a non-existent element?
Issue: Trying to remove an element that doesn't exist in the list.
colors = ['red', 'green', 'blue']
if 'yellow' in colors:
colors.remove('yellow')
print(colors) # Now won't raise ValueError
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.
Issue: The slice doesn't include the desired last element.
numbers = [0, 1, 2, 3, 4, 5]
middle = numbers[2:5] # or numbers[2:]
print(middle[-1]) # Now correctly prints 4
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().
Issue: append() adds the entire list as a single element.
items = [1, 2, 3]
items.extend([4, 5]) # or items += [4, 5]
print(items) # Now correctly shows [1, 2, 3, 4, 5]
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.
Issue: reverse() modifies the list in-place and returns None.
# 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)