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))
OutputThe 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))
OutputThe 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:
- Initialize the list test_list of tuples
- Initialize the values of K and N
- Use a list comprehension to iterate through the tuples in test_list.
- 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.
- If the index is divisible by N, extract the Kth element of the tuple and add it to the result list.
- 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.
OutputThe 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:
- Initialize the list of tuples:
- Initialize the values of K and N
- Use the map() function with a lambda expression to extract the Kth element of every Nth tuple in the
- 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))
OutputThe 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:
- Convert the list of tuples to a numpy array using the numpy.array() function.
- Use array indexing to extract the Kth element of every Nth row in the array.
- 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))
OutputThe 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 - Extract Even elements in Nested Mixed Tuple
Sometimes, while working with Python tuples, we can have a problem in which we need to get all the even elements from the tuple. The tuples can be nested or mixed. This kind of problem can occur in data domains. Let's discuss certain ways in which this task can be performed. Input : test_tuple = (5,
4 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 | 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 - Extracting Priority Elements in Tuple List
Sometimes, while working with Python Records, we can have a problem in which we need to perform extraction of all the priority elements from records, which usually occur as one of the binary element tuple. This kind of problem can have possible application in web development and gaming domains. Let'
5 min read
Python - Extract ith element of K key's value
Given a dictionary, extract ith element of K key's value list. Input : test_dict = {'Gfg' : [6, 7, 3, 1], 'is' : [9, 1, 4], 'best' : [10, 7, 4]}, K = 'Gfg', i = 1 Output : 7 Explanation : 1st index of 'Gfg''s value is 7.Input : test_dict = {'Gfg' : [6, 7, 3, 1], 'is' : [9, 1, 4], 'best' : [10, 7, 4]
6 min read
Python | Convert list of tuples into list
In Python we often need to convert a list of tuples into a flat list, especially when we work with datasets or nested structures. In this article, we will explore various methods to Convert a list of tuples into a list. Using itertools.chain() itertools.chain() is the most efficient way to flatten a
3 min read
Python - Rear element extraction from list of tuples records
While working with tuples, we store different data as different tuple elements. Sometimes, there is a need to print specific information from the tuple like rear index. For instance, a piece of code would want just names to be printed on all the student data. Let's discuss certain ways in which one
8 min read
Python - Get Even indexed elements in Tuple
Sometimes, while working with Python data, one can have a problem in which we need to perform the task of extracting just even indexed elements in tuples. This kind of problem is quite common and can have possible application in many domains such as day-day programming. Let's discuss certain ways in
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 pe
5 min read
Python - Filter Tuples by Kth element from List
Given a list of tuples, filter by Kth element presence in List. Input : test_list = [("GFg", 5, 9), ("is", 4, 3), ("best", 10, 29)], check_list = [4, 2, 3, 10], K = 2 Output : [('is', 4, 3)] Explanation : 3 is 2nd element and present in list, hence filtered tuple. Input : test_list = [("GFg", 5, 9),
5 min read