Python – Extract Paired Rows

PythonServer Side ProgrammingProgramming

Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

Practical Data Science using Python

22 Lectures 6 hours

When it is required to extract paired rows, a list comprehension and the ‘all’ operator is used.

Example

Below is a demonstration of the same

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)

Output

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]]

Explanation

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

• The list comprehension is used to iterate over the elements.

• The ‘all’ operator is used to get the ‘count’ of element, and check if it is divisible by 2.

• If yes, it is converted to a list, and is assigned to a variable.

• This is displayed as output on the console.

Updated on 16-Sep-2021 08:52:55