Skip to content
Related Articles

Related Articles

Improve Article
Python – Rear Kth elements
  • Last Updated : 10 Jul, 2020

Given a list, the task is to extract all Kth elements from rear end.

Input : test_list = [3, 4, 5, 2, 1], K = 2
Output : [1, 5, 3]
Explanation : Every 2nd elements are extracted from rear starting from 1.

Input : test_list = [3, 4, 5], K = 1
Output : [5, 4, 3]
Explanation : Every elements are extracted from rear starting from 1.

Method #1 : Using loop
The is brute method to solve this problem. In this, we reverse and then perform iteration to get each Kth multiple element.




# Python3 code to demonstrate working of 
# Rear Kth elements
# Using loop
  
# initializing list
test_list = [3, 5, 7, 9, 10, 2, 8, 6
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 3
  
# Rear Kth elements
res = []
test_list.reverse()
for idx, ele in enumerate(test_list):
      
    # Extracting elements divisible by K
    if idx % K == 0:
        res.append(ele)
  
# printing result 
print("Rear Kth elements : " + str(res))
Output :



The original list is : [3, 5, 7, 9, 10, 2, 8, 6]
Rear Kth elements : [6, 10, 5]

 

Method #2 : Using list slicing
This is shorthand version solution to this problem. We use power of list slicing skip to skip Kth element, and also reverse it.




# Python3 code to demonstrate working of 
# Rear Kth elements
# Using list slicing
  
# initializing list
test_list = [3, 5, 7, 9, 10, 2, 8, 6
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 3
  
# Rear Kth elements
# Starting slicing from Rear (-1) and extracting all Kth elements
res = test_list[-1::-K]
  
# printing result 
print("Rear Kth elements : " + str(res))
Output :
The original list is : [3, 5, 7, 9, 10, 2, 8, 6]
Rear Kth elements : [6, 10, 5]

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :