Python – K elements Reversed Slice
Given List of elements, perform K elements reverse slice.
Input : test_list = [2, 4, 6, 8, 3, 9, 12, 15, 16, 18], K = 3 Output : [18, 16, 15] Explanation : 3 elements sliced from rear end. Input : test_list = [2, 4, 6, 8], K = 3 Output : [8, 6, 4] Explanation : 3 elements sliced from rear end, 8, 6 and 4.
Method #1 : Using list slicing
This is one of the ways in which this task can be performed. In this, we perform reverse slice using reversing and negative slicing capabilities of list slicing.
Python3
# Python3 code to demonstrate working of# K elements Reversed Slice# Using list slicing# initializing listtest_list = [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]# printing original listprint("The original list : " + str(test_list))# initializing KK = 6# using double slice to solve problem.# "-" sign for slicing from rearres = test_list[-K:][::-1]# printing resultprint("The sliced list : " + str(res)) |
The original list : [2, 4, 6, 8, 3, 9, 12, 15, 16, 18] The sliced list : [18, 16, 15, 12, 9, 3]
Method #2 : Using islice() + reversed()
This is functional approach to solve this problem. In this, we perform slicing using islice(), and then list is reversed using reversed().
Python3
# Python3 code to demonstrate working of# K elements Reversed Slice# Using K elements Reversed Slicefrom itertools import islice# initializing listtest_list = [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]# printing original listprint("The original list : " + str(test_list))# initializing KK = 6# using reversed and islice to slice# and then perform reverseres = list(islice(reversed(test_list), K))# printing resultprint("The sliced list : " + str(res)) |
The original list : [2, 4, 6, 8, 3, 9, 12, 15, 16, 18] The sliced list : [18, 16, 15, 12, 9, 3]


