Python – Extract Paired Rows

PythonServer Side ProgrammingProgramming

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.

raja
Published on 16-Sep-2021 08:52:55
Advertisements