The Wayback Machine - https://web.archive.org/web/20241002142759/https://www.geeksforgeeks.org/python-extract-kth-element-of-every-nth-tuple-in-list/
Open In App

Python – Extract Kth element of every Nth tuple in List

Last Updated : 10 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 = [(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 = 0, N = 3 
Output : [4, 4, 1] 
Explanation : From 0th, 3rd, and 6th tuple, 0th elements are 4, 4, 1.

Method #1 : Using loop

In this, we iterate by skipping N values using 3rd parameter of range(), and append every Kth value in list using loop.

Step-by-step approach:

  • Create an empty list named res.
  • Start a loop using the range() function to iterate over the indices of test_list, with a step of N.
    • Extract the Kth element from the tuple at the current index, and append it to res.
  • Print the extracted elements.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Extract Kth element of every Nth tuple in List
# Using loop
 
# initializing list
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)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 1
 
# initializing N
N = 3
 
res = []
for idx in range(0, len(test_list), N):
     
    # extract Kth element
    res.append(test_list[idx][K])
 
# printing result
print("The extracted elements : " + str(res))


Output

The original list is : [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6, 4, 7), (2, 5, 7), (1, 9, 10), (3, 5, 7)]
The extracted elements : [5, 7, 9]

Time Complexity: O(n), where n is the elements of tuple
Auxiliary Space: O(n), where n is the size of tuple

Method #2 : Using list comprehension

In this, we perform task of extracted elements using one-liner using list comprehension, using same method as above.

Python3




# Python3 code to demonstrate working of
# Extract Kth element of every Nth tuple in List
# Using list comprehension
 
# initializing list
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)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 1
 
# initializing N
N = 3
 
# Skipping N using 3rd param of range()
res = [test_list[idx][K] for idx in range(0, len(test_list), N)]
 
# printing result
print("The extracted elements : " + str(res))


Output

The original list is : [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6, 4, 7), (2, 5, 7), (1, 9, 10), (3, 5, 7)]
The extracted elements : [5, 7, 9]

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

Method #3: Using enumerate

This code extracts the Kth element from every Nth tuple in the list test_list. Here’s the step-by-step algorithm for this approach:

  1. Initialize the list test_list of tuples
  2. Initialize the values of K and N
  3. Use a list comprehension to iterate through the tuples in test_list.
  4. Check if the index of the current tuple is divisible by N using the modulo operator %. If the index is not divisible by N, skip this iteration.
  5. If the index is divisible by N, extract the Kth element of the tuple and add it to the result list.
  6. Return the result list.

Python3




# initializing list
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)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 1
 
# initializing N
N = 3
 
# Extract Kth element of every Nth tuple in List
res = [t[K] for i, t in enumerate(test_list) if i % N == 0]
 
# printing result
print("The extracted elements : " + str(res))
#This code is contributed by Vinay Pinjala.


Output

The original list is : [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6, 4, 7), (2, 5, 7), (1, 9, 10), (3, 5, 7)]
The extracted elements : [5, 7, 9]

Time complexity: O(n), where n is the number of tuples in the list test_list. 
Auxiliary space: O(n), since we are creating a new list to store the extracted elements.

Method 4: Using the map() function with a lambda expression. 

Step-by-step approach:

  1. Initialize the list of tuples:
  2. Initialize the values of K and N
  3. Use the map() function with a lambda expression to extract the Kth element of every Nth tuple in the 
  4. Print the extracted elements

Below is the implementation of the above approach:

Python3




# initializing list
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)]
 
# printing original list
print("The original list is: " + str(test_list))
 
# initializing K
K = 1
 
# initializing N
N = 3
 
# Extract Kth element of every Nth tuple in List using map() and lambda expression
res = list(map(lambda t: t[K], test_list[::N]))
 
# printing result
print("The extracted elements: " + str(res))


Output

The original list is: [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6, 4, 7), (2, 5, 7), (1, 9, 10), (3, 5, 7)]
The extracted elements: [5, 7, 9]

Time complexity: O(n), where n is the length of the input list. 
Auxiliary space: O(n) as we are creating a new list to store the extracted elements.

Method 5: Using numpy array indexing

Step-by-step approach:

  1. Convert the list of tuples to a numpy array using the numpy.array() function.
  2. Use array indexing to extract the Kth element of every Nth row in the array.
  3. Convert the resulting numpy array to a Python list using the .tolist() method.

Python3




import numpy as np
 
# initializing list
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)]
 
# printing original list
print("The original list is: " + str(test_list))
 
# initializing K
K = 1
 
# initializing N
N = 3
 
# Convert the list to a numpy array
arr = np.array(test_list)
 
# Use array indexing to extract the Kth element of every Nth row
res = arr[::N, K].tolist()
 
# printing result
print("The extracted elements: " + str(res))


OUTPUT:

The original list is: [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6, 4, 7), (2, 5, 7), (1, 9, 10), (3, 5, 7)]
The extracted elements: [5, 7, 9]

The time complexity of this method is O(N), where N is the length of the original list. 

The auxiliary space is O(N) as well, because we create a new numpy array to store the data. 

Method 6: Using a generator expression with the yield keyword.

Step-by-step approach:

  • Define a generator function that takes in the list, K and N as parameters.
  • Use a loop to iterate through the indices of the list from 0 to the length of the list, incrementing by N.
  • Use the yield keyword to return the Kth element of the tuple at the current index.
  • Call the generator function with the test list, K, and N.
  • Convert the generator object to a list using the list() function and assign it to the variable res.
  • Print the extracted elements using the print() function and string concatenation.

Below is the implementation of the above approach:

Python3




# initializing list
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)]
 
# printing original list
print("The original list is: " + str(test_list))
 
# initializing K
K = 1
 
# initializing N
N = 3
 
# Define generator function to extract Kth element of every Nth tuple in list
def extract_tuple_element(lst, K, N):
    for i in range(0, len(lst), N):
        yield lst[i][K]
 
# Extract Kth element of every Nth tuple in List using generator expression
res = list(extract_tuple_element(test_list, K, N))
 
# printing result
print("The extracted elements: " + str(res))


Output

The original list is: [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6, 4, 7), (2, 5, 7), (1, 9, 10), (3, 5, 7)]
The extracted elements: [5, 7, 9]

Time complexity: O(N), where N is the length of the list divided by the step size N.
Auxiliary space: O(1), as only constant amount of extra space is used.



Similar Reads

Python | Sort tuple list by Nth element of tuple
Sometimes, while working with Python list, we can come across a problem in which we need to sort the list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using sort(
8 min read
Python | Replace tuple according to Nth tuple element
Sometimes, while working with data, we might have a problem in which we need to replace the entry in which a particular entry of data is matching. This can be a matching phone no, id etc. This has it's application in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + enumerate() This task
8 min read
Python | Insert Nth element to Kth element in other list
Sometimes, while working with Python list, there can be a problem in which we need to perform the inter-list shifts of elements. Having a solution to this problem is always very useful. Let’s discuss the certain way in which this task can be performed. Method 1: Using pop() + insert() + index() This particular task can be performed using a combinat
9 min read
Python | Remove duplicates based on Kth element tuple list
Sometimes, while working with records, we may have a problem in which we need to remove duplicates based on Kth element of a tuple in the list. This problem has application in domains that uses records as input. Let's discuss certain ways in which this problem can be solved. Method #1: Using loop This is a brute-force method to perform this particu
8 min read
Python - Concatenate Kth element in Tuple List
While working with tuples, we store different data as different tuple elements. Sometimes, there is a need to print a specific information from the tuple. For instance, a piece of code would want just names to be printed of all the student data in concatenated format. Lets discuss certain ways how one can achieve solutions to this problem. Method #
8 min read
Python program to convert tuple into list by adding the given string after every element
Given a Tuple. The task is to convert it to List by adding the given string after every element. Examples: Input : test_tup = (5, 6, 7), K = "Gfg" Output : [5, 'Gfg', 6, 'Gfg', 7, 'Gfg'] Explanation : Added "Gfg" as succeeding element. Input : test_tup = (5, 6), K = "Gfg" Output : [5, 'Gfg', 6, 'Gfg'] Explanation : Added "Gfg" as succeeding element
5 min read
Python | Operate on every Kth element of list
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 + enu
5 min read
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 slicing This task can be performed using list slicing
3 min read
Python | Every Kth element removal in List
We generally wish to employ a particular function to all the elements in a list. But sometimes, according to requirement we would wish to remove 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 gett
5 min read
Python | Adding N to Kth tuple element
Many times, while working with records, we can have a problem in which we need to change the value of tuple elements. This is a common problem while working with tuples. Let's discuss certain ways in which N can be added to Kth element of tuple in list. Method #1 : Using loop Using loops this task can be performed. In this, we just iterate the list
3 min read
Python - Closest Pair to Kth index element in Tuple
In the given problem, condition K specifies the maximum allowable difference between corresponding elements of tuples, i.e., it represents the proximity threshold for finding the nearest tuple. The goal is to find the tuple in the list whose elements have the smallest maximum difference compared to the given tuple tup, and this difference should no
7 min read
Python - Insert after every Nth element in a list
Sometimes we need to perform a single insertion in python, this can be easily done with the help of the insert function. But sometimes, we require to insert in a repeated manner after every n numbers, for that there can be numerous shorthands that can be quite handy. Lets discuss certain ways in which this can be done. Method #1 : Using join() + en
7 min read
Python | Counting Nth tuple element
Sometimes, while working with Python, we can have a problem in which we need to count the occurrence of a particular's elements. This kind of problem is quite common while working with records. Let's discuss a way in which this task can be performed. Method #1 : Using Counter() + generator expression The combination of above functionalities can be
5 min read
Python Program to Remove Nth element from Kth key's value from the dictionary
Given a dictionary with value lists, our task is to write a Python program to remove N element from Kth key's values. Examples: Input : test_dict = {"gfg" : [9, 4, 5, 2, 3, 2], "is" : [1, 2, 3, 4, 3, 2], "best" : [2, 2, 2, 3, 4]}, K, N = "gfg", 2Output : {'gfg': [9, 4, 5, 3], 'is': [1, 2, 3, 4, 3, 2], 'best': [2, 2, 2, 3, 4]}Explanation : 2 removed
9 min read
Python - Extract tuple supersets from List
Sometimes, while working with Python tuples, we can have a problem in which we need to extract all the tuples, which have all the elements in target tuple. This problem can have application in domains such as web development. Let's discuss certain way in which this problem can be solved. Input : test_list = [(5, 6, 6), (4, 2, 7), (9, 6, 5, 6)] test
5 min read
Python - Extract digits from Tuple list
Sometimes, while working with Python lists, we can have a problem in which we need to perform extraction of all the digits from tuple list. This kind of problem can find its application in data domains and day-day programming. Let's discuss certain ways in which this task can be performed. Input : test_list = [(15, 3), (3, 9)] Output : [9, 5, 3, 1]
6 min read
Python - Extract Kth index elements from Dictionary Value list
Given a dictionary with list as values, extract all the Kth index elements. Input : {"Gfg" : [4, 7, 5], "Best" : [8, 6, 7], "is" : [9, 3, 8]}, K = 2 Output : [5, 7, 8] Explanation : The 2nd index elements are 5, 7 and 8 respectively in different keys. Input : {"Gfg" : [4, 7, 5], "Best" : [8, 6, 7], "is" : [9, 3, 8]}, K = 0 Output : [4, 8, 9] Explan
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 1st index are removed. Input : test_list = [(5, 3),
4 min read
Python - Flatten tuple of List to tuple
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have listed as their constituent elements. This kind of problem is common in data domains such as Machine Learning. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ([5], [6], [3], [8]) O
7 min read
Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]] Output : [(4, 10), (5, 13)] Explanation : All co
8 min read
Python Program to find tuple indices from other tuple list
Given Tuples list and search list consisting of tuples to search, our task is to write a Python Program to extract indices of matching tuples. Input : test_list = [(4, 5), (7, 6), (1, 0), (3, 4)], search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]Output : [3, 1]Explanation : (3, 4) from search list is found on 3rd index on test_list, hence included in r
8 min read
Python Program to Merge tuple list by overlapping mid tuple
Given two lists that contain tuples as elements, the task is to write a Python program to accommodate tuples from the second list between consecutive tuples from the first list, after considering ranges present between both the consecutive tuples from the first list. Input : test_list1 = [(4, 8), (19, 22), (28, 30), (31, 50)], test_list2 = [(10, 12
11 min read
Python - Consecutive Kth column Difference in Tuple List
Sometimes, while working with Python list, we can have a task in which we need to work with tuple list and get the absolute difference of it’s Kth index. This problem has application in web development domain while working with data informations. Let’s discuss certain ways in which this task can be performed. Examples: Input : test_list = [(5, 4, 2
6 min read
Python | Summation of Kth Column of Tuple List
Sometimes, while working with Python list, we can have a task in which we need to work with tuple list and get the possible accumulation of its Kth index. This problem has applications in the web development domain while working with data information. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehensio
7 min read
Python - Kth Column Product in Tuple List
Sometimes, while working with Python list, we can have a task in which we need to work with tuple list and get the product of it’s Kth index. This problem has application in web development domain while working with data informations. Let’s discuss certain ways in which this task can be performed. Method #1: Using list comprehension + loop This tas
7 min read
Python - Kth Index Tuple List Mean
Sometimes, while working with Python tuple, we can have a problem in which we need to compute average of any particular index of tuples in a list. This kind of problem can have application in data domain such as web development. Let's discuss certain ways in which this task can be performed. Input : test_list = [('Gfg', 1), ('is', 5), ('best', 7)],
6 min read
Python Program For Swapping Kth Node From Beginning With Kth Node From End In A Linked List
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..etc). The pointers are always fixed (4 bytes for most
5 min read
Python | Extract Nth words in Strings List
Sometimes, while working with Python Lists, we can have problems in which we need to perform the task of extracting Nth word of each string in List. This can have applications in the web-development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension + split() The combination of the above meth
7 min read
Python | Minimum K records of Nth index in tuple list
Sometimes, while working with data, we can have a problem in which we need to get the minimum of elements filtered by the Nth element of record. This has a very important utility in web development domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using filter() + lambda + set() + list comprehension The combination
9 min read
Python - Get maximum of Nth column from tuple list
Sometimes, while working with Python lists, we can have a task in which we need to work with tuple list and get the maximum of its Nth index. This problem has application in web development domain while working with data information. Let’s discuss certain ways in which this task can be performed. Method #1: Using list comprehension + max() This tas
7 min read
Practice Tags :