Python – Remove Tuples with difference greater than K

PythonServer Side ProgrammingProgramming

When it is required to remove tuples with difference greater than K, use the abs() method.

Below is a demonstration of the same −

Example

my_tuple = [(41, 18), (21,57), (39, 22), (23, 42), (22, 10)]
print("The tuple is :")
print(my_tuple)
K = 20
my_result = [element for element in my_tuple if abs(element[0] - element[1]) <= K]
print("The result is :")
print(my_result)

Output

The tuple is :
[(41, 18), (21, 57), (39, 22), (23, 42), (22, 10)]
The result is :
[(39, 22), (23, 42), (22, 10)]

Explanation

  • A tuple is defined and displayed on the console.

  • The value for K is defined.

  • A list comprehension is used to iterate over the list, and the difference of each element of the tuple is compared with K.

  • This result is assigned to a variable.

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

raja
Published on 08-Sep-2021 06:45:23
Advertisements