Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python – Extract Kth element of every Nth tuple in List
When working with lists of tuples, you may need to extract the Kth element from every Nth tuple. This can be accomplished using simple iteration with the range() function and list indexing.
Understanding the Problem
Given a list of tuples, we want to:
- Select every Nth tuple (e.g., every 3rd tuple: indices 0, 3, 6...)
- From each selected tuple, extract the Kth element
- Collect these elements into a new list
Example
Below is a demonstration of extracting the 1st element (K=1) from every 3rd tuple (N=3) ?
tuples_list = [(54, 51, 23), (73, 24, 47), (24, 33, 72), (64, 27, 18),
(63, 24, 67), (12, 25, 77), (31, 39, 80), (33, 55, 78)]
print("The list is:")
print(tuples_list)
K = 1 # Extract 1st element (index 1)
N = 3 # Every 3rd tuple
print(f"K = {K} (extract element at index {K})")
print(f"N = {N} (every {N}rd tuple)")
result = []
for index in range(0, len(tuples_list), N):
result.append(tuples_list[index][K])
print("Selected tuples and their Kth elements:")
for index in range(0, len(tuples_list), N):
tuple_data = tuples_list[index]
kth_element = tuple_data[K]
print(f"Tuple at index {index}: {tuple_data} ? Element at K={K}: {kth_element}")
print(f"\nResult: {result}")
The list is: [(54, 51, 23), (73, 24, 47), (24, 33, 72), (64, 27, 18), (63, 24, 67), (12, 25, 77), (31, 39, 80), (33, 55, 78)] K = 1 (extract element at index 1) N = 3 (every 3rd tuple) Selected tuples and their Kth elements: Tuple at index 0: (54, 51, 23) ? Element at K=1: 51 Tuple at index 3: (64, 27, 18) ? Element at K=1: 27 Tuple at index 6: (31, 39, 80) ? Element at K=1: 39 Result: [51, 27, 39]
Using List Comprehension
You can achieve the same result more concisely using list comprehension ?
tuples_list = [(54, 51, 23), (73, 24, 47), (24, 33, 72), (64, 27, 18),
(63, 24, 67), (12, 25, 77), (31, 39, 80), (33, 55, 78)]
K = 1
N = 3
# List comprehension approach
result = [tuples_list[i][K] for i in range(0, len(tuples_list), N)]
print(f"Result using list comprehension: {result}")
Result using list comprehension: [51, 27, 39]
How It Works
-
range(0, len(tuples_list), N)generates indices: 0, 3, 6, 9... (every Nth position) -
tuples_list[index]selects the tuple at that position -
[K]extracts the Kth element from the selected tuple - All extracted elements are collected into the result list
Conclusion
Use range(0, len(list), N) to select every Nth tuple, then index with [K] to extract the desired element. List comprehension provides a more concise alternative to explicit loops for this operation.
Advertisements
