Remove tuples from list of tuples if greater than n in Python

PythonServer Side ProgrammingProgramming

When it is required to remove tuples from a list of tuples if it is greater than a value 'n', the lambda function can be used.

Anonymous function is a function which is defined without a name. In general, functions in Python are defined using 'def' keyword, but anonymous function is defined with the help of 'lambda' keyword.

It takes a single expression, but can take any number of arguments. It uses the expression and returns the result of it.

Below is a demonstration for the same −

Example

Live Demo

my_tuple = [('a', 130), ('b', 230), ('c', 25),('z', 654), ('f', 69)]

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

my_result = [i for i in my_tuple if i[1] >= 100]

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

Output

The list of tuple is :
[('a', 130), ('b', 230), ('c', 25), ('z', 654), ('f', 69)]
The resultant list of tuple is :
[('a', 130), ('b', 230), ('z', 654)]

Explanation

  • A list of tuple is defined, and is displayed on the console.
  • It is iterated over, and checked if any element is greater than or equal to zero.
  • If yes, it is converted into a list.
  • This operation's data is stored in a variable.
  • This variable is the output that is displayed on the console.
raja
Published on 13-Mar-2021 05:42:56
Advertisements