Open In App

Python | Every Kth element in list

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python lists, we can have a problem in which we require to extract every Kth element of list and slice out a new list from that. This type of problems are quite common as a variation of list slicing. Let’s discuss a way in which this can be done. 
Method : Using list slicing This task can be performed using list slicing functionality. The trick here is to use the skip functionality of list to get every Kth element of list. K, as defined can be used as skip element. 

Python3




# Python3 code to demonstrate working of
# Kth element list
# Using list slicing
 
# initializing list
test_list = [6, 4, 8, 9, 10, 5, 8, 9, 10, 2, 34, 5]
 
# printing list
print("The original list : " + str(test_list))
 
# initializing K
K = 3
 
# Kth element list
# Using list slicing
res = test_list[::K]
 
# Printing result
print("Kth element list is : " + str(res))


Output : 

 
The original list : [6, 4, 8, 9, 10, 5, 8, 9, 10, 2, 34, 5]
Kth element list is : [6, 9, 8, 2]

Time Complexity: O(n) where n is the number of elements in the list “test_list”. list slicing performs n number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list

Method : Using itertools

Another approach could be using itertools.islice() method which can take the start position and the step size to extract every Kth element and return it as an iterator, this approach would have a time complexity of O(n) where n is the number of elements in the list, and a space complexity of O(n/k) as it requires a new list to be created.

Python3




import itertools
 
# initializing list
test_list = [6, 4, 8, 9, 10, 5, 8, 9, 10, 2, 34, 5]
   
# printing original list
print("The original list : " + str(test_list))
   
# initializing K
K = 3
   
# Kth element list
# Using itertools.islice()
res = list(itertools.islice(test_list, 0, len(test_list), K))
   
# Printing result
print("Kth element list is : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original list : [6, 4, 8, 9, 10, 5, 8, 9, 10, 2, 34, 5]
Kth element list is : [6, 9, 8, 2]

This code uses the itertools.islice() method to extract every Kth element in the input list and return it as an iterator. Then it converts the iterator to a list and print the result. The parameters passed to the islice method are (iterable, start, stop, step), where iterable is the list, start is the starting index, stop is the ending index, and step is the number of elements to skip before returning the next element. In this case, we start from the first element (index 0), end at the last element of the list, and skip K-1 elements in between. This allows us to extract every Kth element in the list.



Last Updated : 12 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads