Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python program to extract rows with common difference elements



When it is required to extract rows with common difference elements, an iteration and a flag value is used.

Example

Below is a demonstration of the same

my_list = [[31, 27, 10], [8, 11, 12], [11, 12, 13], [6, 9, 10]]

print("The list is :")
print(my_list)

my_result = []

for row in my_list:
   temp = True
   for index in range(0, len(row) - 1):

      if row[index + 1] - row[index] != row[1] - row[0]:
         temp = False
         break

   if temp :
      my_result.append(row)

print("The resultant list is :")
print(my_result)

Output

The list is :
[[31, 27, 10], [8, 11, 12], [11, 12, 13], [6, 9, 10]]
The resultant list is :
[[11, 12, 13]]

Explanation

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

  • An empty list is created.

  • The list is iterated over, and a variable is assigned to ‘True’.

  • The indices are also iterated over.

  • If the difference between previous index and current index is not equal to the difference between the previous element and current element, the variable is assigned ‘False’.

  • The control breaks out of it.

  • In the end, if the variable’s value is ‘True’, the element is appended to the empty list.

  • This is the output that is displayed on the console.

Updated on: 2021-09-14T11:19:36+05:30

111 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements