Python program to find Tuples with positive elements in List of tuples


When it is required to find tuples that have position elements from a list of tuples, list comprehension can be used.

Below is a demonstration of the same −

Example

 Live Demo

my_list = [(56, 43), (-31, 21, 23), (51, -65, 26), (24, 56)]

print("The list is : ")
print(my_list)

my_result = [sub for sub in my_list if all(elem >= 0 for elem in sub)]

print("The positive elements are : ")
print(my_result)

Output

The list is :
[(56, 43), (-31, 21, 23), (51, -65, 26), (24, 56)]
The positive elements are :
[(56, 43), (24, 56)]

Explanation

  • A list of tuples is defined, and is displayed on the console.

  • A list comprehension can be used to iterate through the elements.

  • It is checked to see if every element is greater than 0 or not.

  • If it is greater than 0, it is converted to a list element, and is stored in a variable.

  • This variable is displayed as output on the console.

Updated on: 15-Apr-2021

314 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements