Python Practice › List Programs › Program 83
Remove n elements from the left or right
Write a Python program to remove n elements from the left and from the right of a list.
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
items[n:]drops from the left,items[:-n]from the right.
Solution
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.