Open In App

Python | Custom slicing in List

Sometimes, while working with Python, we can come to a problem in which we need to perform the list slicing. There can be many variants of list slicing. One can have custom slice interval and slicing elements. Let’s discuss problem to such problem. 

Method : Using compress() + cycle() The combination of above functions can be used to perform this particular task. In this, we filter the list for Truth value of required elements and eliminate those which should be skipped by providing then a boolean false. Then the result is accumulated using inbuilt compress() 






# Python3 code to demonstrate working of
# Custom slicing in List
# using compress() + cycle()
from itertools import cycle, compress
 
# initialize lists
test_list = [1, 2, 4, 7, 3, 8, 6, 2, 10, 11, 17, 34, 23, 21]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialize interval
interval = 5
 
# initialize element number
ele_num = 4
 
# Custom slicing in List
# using compress() + cycle()
temp = cycle([True] * ele_num + [False] * interval)
res = list(compress(test_list, temp))
 
# printing result
print("Custom sliced list is : " + str(res))

Output : 
The original list is : [1, 2, 4, 7, 3, 8, 6, 2, 10, 11, 17, 34, 23, 21]
Custom sliced list is : [1, 2, 4, 7, 11, 17, 34, 23]

Time Complexity: O(n), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list 



Using filter() function:

Approach:

We can use the filter() function to perform custom slicing in a list. The filter() function returns an iterator containing the elements from the original list that satisfy a given condition. We can pass a lambda function to the filter() function to specify the condition.




lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
new_lst = list(filter(lambda x: x % 2 == 0, lst))
print(new_lst)

Output
[2, 4, 6, 8, 10]

Time complexity: O(n)
Space complexity: O(n)


Article Tags :