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 – Extract Paired Rows
When working with lists of lists, we sometimes need to extract rows where every element appears an even number of times. This is called extracting "paired rows" since elements come in pairs. Python's list comprehension with the all() function provides an elegant solution.
What are Paired Rows?
A paired row is a list where every element appears an even number of times (2, 4, 6, etc.). For example, [30, 30, 51, 51] is paired because both 30 and 51 appear exactly twice.
Syntax
result = [row for row in list_of_lists if all(row.count(element) % 2 == 0 for element in row)]
Example
Let's extract rows where all elements appear in pairs −
my_list = [[10, 21, 34, 21, 37], [41, 41, 52, 68, 68, 41], [12, 29], [30, 30, 51, 51]]
print("The list is :")
print(my_list)
my_result = [row for row in my_list if all(row.count(element) % 2 == 0 for element in row)]
print("The result is :")
print(my_result)
The list is : [[10, 21, 34, 21, 37], [41, 41, 52, 68, 68, 41], [12, 29], [30, 30, 51, 51]] The result is : [[30, 30, 51, 51]]
How It Works
The solution breaks down into these steps:
List comprehension − Iterates through each row in the main list
all() function − Checks that every element in the row satisfies the condition
count() method − Counts how many times each element appears in the row
Modulo operator (%) − Checks if the count is divisible by 2 (even number)
Analysis of Each Row
| Row | Element Counts | All Even? | Result |
|---|---|---|---|
| [10, 21, 34, 21, 37] | 10:1, 21:2, 34:1, 37:1 | No | Excluded |
| [41, 41, 52, 68, 68, 41] | 41:3, 52:1, 68:2 | No | Excluded |
| [12, 29] | 12:1, 29:1 | No | Excluded |
| [30, 30, 51, 51] | 30:2, 51:2 | Yes | Included |
Alternative Approach Using Function
For better readability, you can create a separate function −
def is_paired_row(row):
return all(row.count(element) % 2 == 0 for element in row)
my_list = [[10, 21, 34, 21, 37], [41, 41, 52, 68, 68, 41], [12, 29], [30, 30, 51, 51]]
paired_rows = [row for row in my_list if is_paired_row(row)]
print("Paired rows:", paired_rows)
Paired rows: [[30, 30, 51, 51]]
Conclusion
Use list comprehension with all() and count() to extract paired rows efficiently. The all() function ensures every element in a row appears an even number of times, making this approach both readable and performant.
