Python - Filter consecutive elements Tuples
Last Updated :
15 May, 2023
Given a Tuple list, filter tuples that are made from consecutive elements, i.e diff is 1.
Input : test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 4), (6, 4, 6, 3)]
Output : [(3, 4, 5, 6)]
Explanation : Only 1 tuple adheres to condition.
Input : test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6, 4, 6, 3)]
Output : [(3, 4, 5, 6), (1, 2, 3)]
Explanation : Only 2 tuples adhere to condition.
Method #1: Using loop
In this, for each tuple, we call consecutive elements utility which returns True if tuple is consecutive.
Python3
# Python3 code to demonstrate working of
# Filter consecutive elements Tuples
# Using loop
# hlpr_func
def consec_check(tup):
for idx in range(len(tup) - 1):
# returns false if any element is not consec.
if tup[idx + 1] != tup[idx] + 1:
return False
return True
# initializing list
test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6, 4, 6, 3)]
# printing original list
print("The original list is : " + str(test_list))
res = []
for sub in test_list:
# calls fnc to check consec.
if consec_check(sub):
res.append(sub)
# printing result
print("The filtered tuples : " + str(res))
OutputThe original list is : [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6, 4, 6, 3)]
The filtered tuples : [(3, 4, 5, 6), (1, 2, 3)]
Time Complexity: O(n*n), where n is the length of the input list.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”.
Method #2: Using list comprehension
In this, we perform a similar function as above, just in one-liner shorthand using list comprehension.
Python3
# Python3 code to demonstrate working of
# Filter consecutive elements Tuples
# Using list comprehension
# hlpr_func
def consec_check(tup):
for idx in range(len(tup) - 1):
# returns false if any element is not consec.
if tup[idx + 1] != tup[idx] + 1:
return False
return True
# initializing list
test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6, 4, 6, 3)]
# printing original list
print("The original list is : " + str(test_list))
# one-liner to solve problem, using list comprehension
res = [sub for sub in test_list if consec_check(sub)]
# printing result
print("The filtered tuples : " + str(res))
OutputThe original list is : [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6, 4, 6, 3)]
The filtered tuples : [(3, 4, 5, 6), (1, 2, 3)]
Method #3 : Using min(),max() and range() methods
Python3
# Python3 code to demonstrate working of
# Filter consecutive elements Tuples
# Using loop
# initializing list
test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6, 4, 6, 3)]
# printing original list
print("The original list is : " + str(test_list))
res = []
for i in test_list:
x=list(i)
a=min(x)
b=max(x)
y=list(range(a,b+1))
if(x==y):
res.append(i)
# printing result
print("The filtered tuples : " + str(res))
OutputThe original list is : [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6, 4, 6, 3)]
The filtered tuples : [(3, 4, 5, 6), (1, 2, 3)]
Method #4: Using the set() function.
Here are the steps:
- Initialize an empty list res to store the filtered tuples.
- Loop through each tuple i in the test_list.
- Convert i into a set using the set() function and store it in a variable s.
- Create a set expected using the set() function with the values in the range between the minimum and maximum values of i inclusive.
- If s and expected are equal, append i to the res list.
- Return the res list.
Python3
test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6, 4, 6, 3)]
print("The original list is : " + str(test_list))
res = []
for i in test_list:
s = set(i)
expected = set(range(min(i), max(i)+1))
if s == expected:
res.append(i)
print("The filtered tuples : " + str(res))
OutputThe original list is : [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6, 4, 6, 3)]
The filtered tuples : [(3, 4, 5, 6), (1, 2, 3)]
Time complexity: O(n*k), where n is the number of tuples in the input list and k is the length of the longest tuple.
Auxiliary space: O(k) to store the sets s and expected.
Method #5: Using lambda function and filter() function with slicing
Step by step algorithm:
- Define the input list of tuples.
- Use the filter() function along with a lambda function to filter out non-consecutive tuples.
- Inside the lambda function, for each tuple x in the input list, check if it is equal to a tuple of consecutive integers using the range() function.
- If the tuple is consecutive, it is added to a new list res.
- Convert the filtered list of tuples to a list using the list() function.
- Print the filtered list of tuples.
Python3
# Define a list of tuples to filter
test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6, 4, 6, 3)]
print("The original list is : " + str(test_list))
# Use the filter() function and a lambda function to filter out non-consecutive tuples
# The lambda function checks if each tuple is equal to a tuple of consecutive integers
res = list(filter(lambda x: x == tuple(range(x[0], x[-1]+1)), test_list))
# Print the filtered tuples
print("The filtered tuples : " + str(res))
OutputThe original list is : [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6, 4, 6, 3)]
The filtered tuples : [(3, 4, 5, 6), (1, 2, 3)]
Time Complexity: O(nm), where n is the length of the input list and m is the maximum length of a tuple in the list.
Space Complexity: O(n), where n is the length of the input list.
Similar Reads
Python - Test Consecutive Element Matrix
Given a Matrix, test if it is made of consecutive elements. Input : test_list = [[4, 5, 6], [7], [8, 9, 10], [11, 12]] Output : True Explanation : Elements in Matrix range from 4 to 12. Input : test_list = [[4, 5, 6], [7], [8, 18, 10], [11, 12]] Output : False Explanation : Elements not consecutive
6 min read
Python - Reorder for consecutive elements
Given a List perform reordering to get similar elements in consecution. Input : test_list = [4, 7, 5, 4, 1, 4, 1, 6, 7, 5] Output : [4, 4, 4, 7, 7, 5, 5, 1, 1, 6] Explanation : All similar elements are assigned to be consecutive. Input : test_list = [4, 7, 5, 1, 4, 1, 6, 7, 5] Output : [4, 4, 7, 7,
4 min read
Python - Extend consecutive tuples
Given list of tuples, join consecutive tuples. Input : test_list = [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)] Output : [(3, 5, 6, 7, 3, 2, 4, 3), (3, 2, 4, 3, 9, 4), (9, 4, 2, 3, 2)] Explanation : Elements joined with their consecutive tuples. Input : test_list = [(3, 5, 6, 7), (3, 2, 4, 3)] Ou
3 min read
Python - Concatenate consecutive elements in Tuple
Sometimes, while working with data, we can have a problem in which we need to find cumulative results. This can be of any type, product, or summation. Here we are gonna discuss adjacent element concatenation. Letâs discuss certain ways in which this task can be performed. Method #1 : Using zip() + g
4 min read
Python | Retain K consecutive elements
Sometimes while working with data, we can have a problem in which we need to select some of the elements that occur K times consecutively. This problem can occur in many domains. Let's discuss certain ways in which this problem can be solved. Method #1 : Using groupby() + list comprehension This t
8 min read
Python - Consecutive Tuple difference
Given List of tuples, find index-wise absolute difference of consecutive tuples. Input : test_list = [(5, 3), (1, 4), (9, 5), (3, 5)] Output : [(4, 1), (7, 1), (6, 0)] Explanation : 5 - 1 = 4, 4 - 3 = 1. hence (4, 1) and so on. Input : test_list = [(9, 5), (3, 5)] Output : [(6, 0)] Explanation : 9 -
4 min read
Python | Consecutive elements pairing in list
This process involves creating pairs of elements that appear next to each other, which can be invaluable for various applications such as data analysis, pattern recognition and algorithm development. We can achieve this using different methods in Python, such as using simple loops, list slicing, zip
3 min read
Python - Group Consecutive elements by Sign
Given a list group of consecutive elements on the basis of signs. Input : test_list = [5, -3, 2, 4, 6, -2, -1, -7, -9, 2, 3]Â Output : [[5], [-3], [2, 4, 6], [-2, -1, -7, -9], [2, 3]]Â Explanation : Elements inserted into new list on sign change.Input : test_list = [-2,3,4,5,6,-3] Output : [[-2], [3
3 min read
Python - Similar Consecutive elements frequency
Sometimes, while working with Python, we can have a problem in which we have to find the occurrences of elements that are present consecutively. This problem have usage in school programming and data engineering. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop
5 min read
Python | Group consecutive list elements with tolerance
Sometimes, we might need to group list according to the consecutive elements in the list. But a useful variation of this can also be a case in which we need to consider a tolerance level, i.e allowing a skip value between numbers and not being exactly consecutive but a "gap" is allowed between numbe
3 min read