Python Practice › List Programs › Program 18
Remove the 1st, 3rd and 6th elements
Write a Python program to remove the 1st, 3rd and 6th elements of a list.
Input
["a", "b", "c", "d", "e", "f", "g"]
Output
['b', 'd', 'e', 'g']
Approach
- Keep items whose index is not 0, 2 or 5.
Solution
items = ["a", "b", "c", "d", "e", "f", "g"]remove = {0, 2, 5}print([x for i, x in enumerate(items) if i not in remove])Output
['b', 'd', 'e', 'g']
Line by line
Line 2
Positions 1, 3 and 6 are indexes 0, 2 and 5.
Note
Deleting with del one by one shifts later indexes; building a new list avoids that trap.
Learn the concept
New to this topic? Read the lesson, then come back.