# Python | Retain K Front and Rear elements

• Last Updated : 19 Feb, 2020

Sometimes, we require to shrink a list by deletion of its certain elements. One of the methods that is employed to perform this particular task is front and rear element retention and deletion of rest elements. It is a good utility whose solution can be useful to have. Let’s discuss certain ways in which this can be performed.

Method #1 : Using list slicing + del operator
The del operator can be clubbed with the slicing action to delete all but the front and rear elements from a list to obtain a cropped version of list.

 `# Python3 code to demonstrate ``# Retain K Front and Rear elements``# using del operator + list slicing`` ` `# initializing list ``test_list ``=` `[``2``, ``3``, ``5``, ``7``, ``9``, ``10``, ``8``, ``6``]`` ` `# printing original list``print` `(``"The original list is : "` `+` `str``(test_list))`` ` `# initializing K ``K ``=` `2`` ` `# using del operator + list slicing``# Retain K Front and Rear elements ``N ``=` `len``(test_list)``del` `test_list[K : N ``-` `K]`` ` `# printing result ``print` `(``"The cropped list is : "` `+` `str``(test_list))`
Output :
```The original list is : [2, 3, 5, 7, 9, 10, 8, 6]
The cropped list is : [2, 3, 8, 6]
```

Method #2 : Using list slicing
Above method can be modified and the use of del operator can be omitted to achieve this particular task. We can slice a list in a way that specific number of elements are removed from the list.

 `# Python3 code to demonstrate ``# Retain K Front and Rear elements``# using list slicing`` ` `# initializing list ``test_list ``=` `[``2``, ``3``, ``5``, ``7``, ``9``, ``10``, ``8``, ``6``]`` ` `# printing original list``print` `(``"The original list is : "` `+` `str``(test_list))`` ` `# initializing K ``K ``=` `2`` ` `# using list slicing``# Retain K Front and Rear elements``res ``=` `test_list[: K] ``+` `test_list[``-``K :]`` ` `# printing result ``print` `(``"The cropped list is : "` `+` `str``(res))`
Output :
```The original list is : [2, 3, 5, 7, 9, 10, 8, 6]
The cropped list is : [2, 3, 8, 6]
```

My Personal Notes arrow_drop_up