﻿ Python: Get a list with n elements removed from the left, right - w3resource

# Python: Get a list with n elements removed from the left, right

## Python List: Exercise - 268 with Solution

Write a Python program to get a list with n elements removed from the left, right.

Removed from the left:

• Use slice notation to remove the specified number of elements from the left.
• Omit the last argument, n, to use a default value of 1.

Removed from the right:

Returns a list with n elements removed from the right.

• Use slice notation to remove the specified number of elements from the right.
• Omit the last argument, n, to use a default value of 1.

Sample Solution:

Python Code:

``````def drop_left_right(a, n = 1):
return a[n:], a[:-n]
nums = [1, 2, 3]
print("Original list elements:")
print(nums)
result = drop_left_right(nums)
print("Remove 1 element from left of the said list:")
print(result[0])
print("Remove 1 element from right of the said list:")
print(result[1])
nums = [1, 2, 3, 4]
print("\nOriginal list elements:")
print(nums)
result = drop_left_right(nums,2)
print("Remove 2 elements from left of the said list:")
print(result[0])
print("Remove 2 elements from right of the said list:")
print(result[1])
nums = [1, 2, 3, 4, 5, 6]
print("\nOriginal list elements:")
print(nums)
result = drop_left_right(nums)
print("Remove 7 elements from left of the said list:")
print(result[0])
print("Remove 7 elements from right of the said list:")
print(result[1])
```
```

Sample Output:

```Original list elements:
[1, 2, 3]
Remove 1 element from left of the said list:
[2, 3]
Remove 1 element from right of the said list:
[1, 2]

Original list elements:
[1, 2, 3, 4]
Remove 2 elements from left of the said list:
[3, 4]
Remove 2 elements from right of the said list:
[1, 2]

Original list elements:
[1, 2, 3, 4, 5, 6]
Remove 7 elements from left of the said list:
[2, 3, 4, 5, 6]
Remove 7 elements from right of the said list:
[1, 2, 3, 4, 5]
```

Flowchart:

## Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz

﻿

## Python: Tips of the Day

Floor Division:

When we speak of division we normally mean (/) float division operator, this will give a precise result in float format with decimals.

For a rounded integer result there is (//) floor division operator in Python. Floor division will only give integer results that are round numbers.

```print(1000 // 300)
print(1000 / 300)```

Output:

```3
3.3333333333333335```