When it is required to return rows that have an element at a specified index, a simple iteration and the ‘append’ function can be used.
Example
Below is a demonstration of the same
my_list_1 = [[21, 81, 35], [91, 14, 0], [64, 61, 42]] my_list_2 = [[21, 92, 63], [80, 19, 65], [54, 65, 36]] print("The first list is :") print(my_list_1) print("The second list is :") print(my_list_2) my_key = 0 my_result = [] for index in range(len(my_list_1)): if my_list_1[index][my_key] == my_list_2[index][my_key]: my_result.append(my_list_1[index]) my_result.append(my_list_1[index]) print("The result is :") print(my_result)
Output
The first list is : [[21, 81, 35], [91, 14, 0], [64, 61, 42]] The second list is : [[21, 92, 63], [80, 19, 65], [54, 65, 36]] The result is : [[21, 81, 35], [21, 81, 35]]
Explanation
Two nested lists are defined and are displayed on the console.
A key, i.e index value is defined.
An empty list is defined.
The first list is iterated over, and if the indices of the first and second index elements match, the value is appended to the empty list.
This is the result that is displayed on the console.