Python Practice › List Programs › Program 18

Remove the 1st, 3rd and 6th elements

EasyList Programs · 18 of 100

Write a Python program to remove the 1st, 3rd and 6th elements of a list.

Advertisement
Input
["a", "b", "c", "d", "e", "f", "g"]
Output
['b', 'd', 'e', 'g']

Approach

  1. Keep items whose index is not 0, 2 or 5.

Solution

Python
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.

More list programs

← All 100 List Programs

Leave a Comment