Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Multiply K to every Nth element
Next article icon

Python | Operate on every Kth element of list

Last Updated : 25 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

We generally wish to employ a particular function to all the elements in a list. But sometimes, according to the requirement, we would wish to employ a particular functionality to certain elements of the list, basically to every Kth element in list. Let’s discuss certain ways in which this can be performed.

Method #1: Using list comprehension + enumerate() The functionality of getting every Kth number of list can be done with the help of list comprehension and enumerate function helps in the iteration of the whole list. 

Python3




# Python3 code to demonstrate
# Edit every Kth element in list
# using list comprehension + enumerate()
 
# initializing list
test_list = [1, 4, 5, 6, 7, 8, 9, 12]
 
# printing the original list
print ("The original list is : " + str(test_list))
 
# using list comprehension + enumerate()
# Edit every Kth element in list
# add 2 to every 3rd element
res = [i + 2 if j % 3 == 0 else i
    for j, i in enumerate(test_list)]
 
# printing result
print ("The list after editing every kth element : " + str(res))
 
 
Output
The original list is : [1, 4, 5, 6, 7, 8, 9, 12] The list after editing every kth element : [3, 4, 5, 8, 7, 8, 11, 12]

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

Method #2: Using list comprehension + list slicing Above mentioned functions can help to perform these tasks. The list comprehension does the task of iteration in list and list slicing does the extraction of every Kth element. 

Python3




# Python3 code to demonstrate
# Edit every Kth element in list
# using list comprehension + list slicing
 
# initializing list
test_list = [1, 4, 5, 6, 7, 8, 9, 12]
 
# printing the original list
print ("The original list is : " + str(test_list))
 
# using list comprehension + list slicing
# Edit every Kth element in list
# add 2 to every 3rd element
test_list[0::3] = [i + 2 for i in test_list[0 :: 3]]
 
# printing result
print ("The list after editing every kth element : "
                                   + str(test_list))
 
 
Output:
The original list is : [1, 4, 5, 6, 7, 8, 9, 12] The list after editing every kth element : [3, 4, 5, 8, 7, 8, 11, 12]

Time Complexity: O(n), where n is the length of test_list 
Auxiliary Space: O(1)

Method #3:Using range function

Python3




# Python3 code to demonstrate
# Edit every Kth element in list
 
# initializing list
test_list = [1, 4, 5, 6, 7, 8, 9, 12]
 
# printing the original list
print("The original list is :" + str(test_list))
 
for i in range(0, len(test_list), 3):
    # Edit every Kth element in list
    # add 2 to every 3rd element
    test_list[i] = test_list[i]+2
 
 
# printing result
print("The list after editing every kth element:" + str(test_list))
 
 
Output
The original list is :[1, 4, 5, 6, 7, 8, 9, 12] The list after editing every kth element:[3, 4, 5, 8, 7, 8, 11, 12]

Time Complexity: O(n), where n is the length of the list, since we are iterating over each element of the list once.
Auxiliary Space: O(1), since we are not creating any new data structures that scale with the size of the input. We are simply modifying the existing list in place.

Method #4:Using itertools module and the islice function

To operate on every Kth element of a list , you can use the itertools module and the islice function. Here is an example of how to add 2 to every 3rd element of a list using islice:

Python3




from itertools import islice
 
# Initialize the list
test_list = [1, 4, 5, 6, 7, 8, 9, 12]
 
# Print the original list
print("The original list is:", test_list)
 
# Use islice and itertools to add 2 to every 3rd element
test_list[::3] = [x+2 for x in islice(test_list, 0, None, 3)]
 
# Print the modified list
print("The modified list is:", test_list)
#This code is contributed by Edula Vinay Kumar Reddy
 
 
Output
The original list is: [1, 4, 5, 6, 7, 8, 9, 12] The modified list is: [3, 4, 5, 8, 7, 8, 11, 12]

Time complexity: O(n), where n is the length of the list.
Auxiliary space: O(n), where n is the length of the list.

Method #5: Using a for loop

 Here is the step-by-step algorithm for implementing the approach in the code:

  1. Initialize a list test_list with some integer values.
  2. Print the original list test_list.
  3. Use a for loop to iterate through the indices of test_list in steps of 3.
  4. Within the loop, add 2 to the value at the current index.
  5. Print the modified list test_list.

Python3




# Initialize the list
test_list = [1, 4, 5, 6, 7, 8, 9, 12]
 
# Print the original list
print("The original list is:", test_list)
 
# Add 2 to every 3rd element using a for loop
for i in range(0,len(test_list), 3):
    test_list[i] += 2
 
# Print the modified list
print("The modified list is:", test_list)
#This code is contributed Vinay Pinjala.
 
 
Output
The original list is: [1, 4, 5, 6, 7, 8, 9, 12] The modified list is: [3, 4, 5, 8, 7, 8, 11, 12]

Time complexity: O(n), where n is the length of the input list. This is because the for loop iterates over each index in the list once, and the addition operation takes constant time. Therefore, the time taken by the algorithm grows linearly with the size of the input.
Auxiliary space: O(1), which is constant space complexity. This is because the algorithm only modifies the original input list and does not create any additional data structures. Therefore, the space taken by the algorithm remains constant regardless of the size of the input.



Next Article
Python - Multiply K to every Nth element
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python | Every Kth element in list
    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 sli
    3 min read
  • Python - Multiply K to every Nth element
    We generally wish to employ a particular function to all the elements in a list. But sometimes, according to requirement we would wish to employ a particular functionality to certain elements of the list, basically to every Nth element in list. Let’s discuss certain ways in which this can be perform
    5 min read
  • Python - Extract Kth element of every Nth tuple in List
    Given list of tuples, extract Kth column element of every Nth tuple. Input :test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6, 4, 7), (2, 5, 7), (1, 9, 10), (3, 5, 7)], K = 2, N = 3 Output : [3, 8, 10] Explanation : From 0th, 3rd, and 6th tuple, 2nd elements are 3, 8, 10. Input :test_list
    8 min read
  • Insert after every Nth element in a list - Python
    Inserting an element after every Nth item in a list is a useful way to adjust the structure of a list. For Example we have a list li=[1,2,3,4,5,6,7] Let's suppose we want to insert element 'x' after every 2 elements in the list so the list will look like li=[1,2,'x',3,4,'x',5,6,7] Iteration with ind
    4 min read
  • Python | Product of kth column in List of Lists
    Sometimes, while working with Python Matrix, we may have a problem in which we require to find the product of a particular column. This can have a possible application in day-day programming and competitive programming. Let’s discuss certain ways in which this task can be performed. Method #1 : Usin
    4 min read
  • Python - Operation to each element in list
    Given a list, there are often when performing a specific operation on each element is necessary. While using loops is a straightforward approach, Python provides several concise and efficient methods to achieve this. In this article, we will explore different operations for each element in the list.
    3 min read
  • Python - Find Kth Even Element
    Given a List, extract Kth occurrence of Even Element. Input : test_list = [4, 6, 2, 3, 8, 9, 10, 11], K = 3 Output : 8 Explanation : K = 3, i.e 0 based index, 4, 6, 2 and 4th is 8. Input : test_list = [4, 6, 2, 3, 8, 9, 10, 11], K = 2 Output : 2 Explanation : K = 2, i.e 0 based index, 4, 6, and 3rd
    5 min read
  • Python - Match Kth number digit in list elements
    Sometimes we may face a problem in which we need to find a list if it contains numbers at the Kth index with the same digits. This particular utility has an application in day-day programming. Let’s discuss certain ways in which this task can be achieved. Method #1 : Using list comprehension + map()
    7 min read
  • Python - Extract records if Kth elements not in List
    Given list of tuples, task is to extract all the tuples where Kth index elements are not present in argument list. Input : test_list = [(5, 3), (7, 4), (1, 3), (7, 8), (0, 6)], arg_list = [6, 8, 8], K = 1 Output : [(5, 3), (7, 4), (1, 3)] Explanation : All the elements which have either 6 or 8 at 1s
    4 min read
  • Python | Get Last N Elements from Given List
    This article discusses ways to fetch the last N elements of a list in Python. Example: Using list Slicing [GFGTABS] Python test_list = [4, 5, 2, 6, 7, 8, 10] # initializing N N = 5 # using list slicing res = test_list[-N:] print(str(res)) [/GFGTABS]Output[2, 6, 7, 8, 10] Explaination: This problem c
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences