Python – Extract Kth element of every Nth tuple in List


When it is required to extract ‘K’th element of every ‘N’th tuple in a list, a simple iteration and the ‘append’ method is used.

Example

Below is a demonstration of the same −

my_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(my_list)

K = 1
print("The value of K is :")
print(K)

N = 3
print("The value of N is :")
print(N)

my_result = []

for index in range(0, len(my_list), N):
   my_result.append(my_list[index][K])

print("The result is :")
print(my_result)

Output

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)]
The value of K is :
1
The value of N is :
3
The result is :
[51, 27, 39]

Explanation

  • A list of tuple is defined and is displayed on the console.

  • The values for K and N are defined and are displayed on the console.

  • An empty list is defined.

  • The list is iterated over, and the element at a specific index at ‘K’ is appended to the empty list

  • This is the output that is displayed on the console.

Updated on: 08-Sep-2021

170 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements