Python Practice › List Programs › Program 83

Remove n elements from the left or right

EasyList Programs · 83 of 100

Write a Python program to remove n elements from the left and from the right of a list.

Advertisement
Input
[2, 5, 7, 9, 3, 4], n = 1 and 2
Output
remove 1 from left: [5, 7, 9, 3, 4] | from right: [2, 5, 7, 9, 3]
remove 2 from left: [7, 9, 3, 4] | from right: [2, 5, 7, 9]

Approach

  1. items[n:] drops from the left, items[:-n] from the right.

Solution

Python
items = [2, 5, 7, 9, 3, 4]for n in [1, 2]:    print(f"remove {n} from left:", items[n:], f"| from right:", items[:-n])
Output
remove 1 from left: [5, 7, 9, 3, 4] | from right: [2, 5, 7, 9, 3]
remove 2 from left: [7, 9, 3, 4] | from right: [2, 5, 7, 9]

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Leave a Comment