Q:

Python program to find tuples with positive elements in list of tuples

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of an ordered set of values enclosed in square brackets [].

Example:

list = [3 ,1,  5, 7]

Finding Tuples with positive elements in list of Tuples

We will be traversing all the tuples of the list and then check if all elements of each tuple.

Input:
[(4, 1), (9, -1), (5, -7)]

Output:
[(4, 1)]

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

To find all the tuples of the list that consist of only positive values. For performing this task, we will use the filter() method and check the condition that all values are positive using the lambda function and all().

# Python program to find Tuples 
# with positive elements in list 

# Creating a new list and 
tupList = [(4, 1), (9, -1), (5, -7)]
print("The original list is : " + str(tupList))

# Finding Tuples with Positive elements in list 
positiveList = list(filter(lambda tup: all(val >= 0 for val in tup), tupList))

# Printing filtered tuple 
print("Tuples with positive values : " + str(positiveList))

Output:

The original list is : [(4, 1), (9, -1), (5, -7)]
Tuples with positive values : [(4, 1)]

Method 2:

Another method to solve the problem is using the list comprehension technique to find the tuples from the list which consist of only positive elements. We will use all methods to test the condition on all elements of the tuple.

# Python program to find Tuples 
# with positive elements in list 

# Creating a new list and 
tupList = [(4, 1), (9, -1), (5, -7)]
print("The original list is : " + str(tupList))

# Finding Tuples with Positive elements in list 
positiveList = [tup for tup in tupList if all(val >= 0 for val in tup)]

# Printing filtered tuple 
print("Tuples with positive values : " + str(positiveList))

Output:

The original list is : [(4, 1), (9, -1), (5, -7)]
Tuples with positive values : [(4, 1)]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to find the frequency of all tuple ... >>
<< Python program to sort tuples by their maximum ele...