Python | Indices of Kth element value
Sometimes, while working with records, we might have a problem in which we need to find all the indices of elements for a particular value at a particular Kth position of tuple. This seems to be a peculiar problem but while working with many keys in records, we encounter this problem. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using loop
This is the brute force method by which this problem can be solved. In this, we keep a counter for indices and append to list if we find the specific record at Kth position in tuple.
# Python3 code to demonstrate working of # Indices of Kth element value # Using loop # initialize list test_list = [( 3 , 1 , 5 ), ( 1 , 3 , 6 ), ( 2 , 5 , 7 ), ( 5 , 2 , 8 ), ( 6 , 3 , 0 )] # printing original list print ( "The original list is : " + str (test_list)) # initialize ele ele = 3 # initialize K K = 1 # Indices of Kth element value # Using loop # using y for K = 1 res = [] count = 0 for x, y, z in test_list: if y = = ele: res.append(count) count = count + 1 # printing result print ( "The indices of element at Kth position : " + str (res)) |
The original list is : [(3, 1, 5), (1, 3, 6), (2, 5, 7), (5, 2, 8), (6, 3, 0)]
The indices of element at Kth position : [1, 4]
Method #2 : Using enumerate()
+ list comprehension
The combination of above functions can be used to solve this problem. In this, we enumerate for the indices using enumerate()
, rest is performed as in above method but in a compact way.
# Python3 code to demonstrate working of # Indices of Kth element value # Using enumerate() + list comprehension # initialize list test_list = [( 3 , 1 , 5 ), ( 1 , 3 , 6 ), ( 2 , 5 , 7 ), ( 5 , 2 , 8 ), ( 6 , 3 , 0 )] # printing original list print ( "The original list is : " + str (test_list)) # initialize ele ele = 3 # initialize K K = 1 # Indices of Kth element value # Using enumerate() + list comprehension res = [a for a, b in enumerate (test_list) if b[K] = = ele] # printing result print ( "The indices of element at Kth position : " + str (res)) |
The original list is : [(3, 1, 5), (1, 3, 6), (2, 5, 7), (5, 2, 8), (6, 3, 0)]
The indices of element at Kth position : [1, 4]