Python – Filter consecutive elements Tuples

PythonServer Side ProgrammingProgramming

When it is required to filter consecutive elements from a list of tuple, a method is defined that takes a list of tuple as a parameter and checks the index of every tuple, and returns a Boolean value depending on the index.

Example

Below is a demonstration of the same −

print("Method definition begins...")
def check_consec_tuple_elem(my_tuple):
   for idx in range(len(my_tuple) - 1):
      if my_tuple[idx + 1] != my_tuple[idx] + 1:
         return False
   return True
print("Method definition ends...")
my_tuple = [(23, 24, 25, 26), (65, 66, 78, 29), (11, 28, 39), (60, 61, 62, 63)]

print("The list of tuple is : " )
print(my_tuple)

my_result = []

for elem in my_tuple:
   if check_consec_tuple_elem(elem):
      my_result.append(elem)

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

Output

Method definition begins...
Method definition ends...
The list of tuple is :
[(23, 24, 25, 26), (65, 66, 78, 29), (11, 28, 39), (60, 61, 62, 63)]
The resultant tuple is :
[(23, 24, 25, 26), (60, 61, 62, 63)]

Explanation

  • A method named ‘check_consec_tuple_elem’ is defined that takes a tuple as a parameter.

  • It iterates through the tuple and checks to see if element at an index and the element at the same index incremented by 1 are equal.

  • If not, it returns False.

  • Outside the method, a list of tuple is defined and is displayed on the console.

  • An empty list is defined.

  • The list of tuple is iterated over, and the method is called by passing every tuple to it.

  • The result of this is appended to the empty list.

  • This list is displayed as the output on the console.

raja
Published on 13-Sep-2021 11:06:53
Advertisements