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
Python program to return rows that have element at a specified index
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. This technique is useful for filtering rows based on matching elements at specific positions.
Basic Example
Below is a demonstration of comparing elements at a specific index ?
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])
print("The result is :")
print(my_result)
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]]
Using List Comprehension
A more concise approach using list comprehension ?
my_list_1 = [[21, 81, 35], [91, 14, 0], [64, 61, 42]]
my_list_2 = [[21, 92, 63], [80, 19, 65], [54, 65, 36]]
my_key = 0
my_result = [row for i, row in enumerate(my_list_1)
if row[my_key] == my_list_2[i][my_key]]
print("The result using list comprehension:")
print(my_result)
The result using list comprehension: [[21, 81, 35]]
Finding Rows with Specific Element
Return rows that have a specific element at a given index ?
data = [[10, 20, 30], [40, 50, 60], [10, 80, 90], [70, 10, 100]]
target_element = 10
target_index = 0
matching_rows = []
for row in data:
if row[target_index] == target_element:
matching_rows.append(row)
print("Original data:")
print(data)
print(f"Rows with element {target_element} at index {target_index}:")
print(matching_rows)
Original data: [[10, 20, 30], [40, 50, 60], [10, 80, 90], [70, 10, 100]] Rows with element 10 at index 0: [[10, 20, 30], [10, 80, 90]]
How It Works
Two nested lists are defined and displayed on the console.
A key (index value) is defined to specify which column to compare.
An empty list is defined to store matching rows.
The lists are iterated over, and if the elements at the specified index match, the row is appended to the result list.
The filtered result is displayed on the console.
Conclusion
Use simple iteration with conditional checks to filter rows based on elements at specific indices. List comprehension provides a more concise alternative for the same functionality.
