
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extract Rows with Common Difference Elements in Python
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.
Advertisements