The Wayback Machine - https://web.archive.org/web/20240930203135/https://www.geeksforgeeks.org/python-program-to-find-tuples-with-positive-elements-in-list-of-tuples/
Open In App

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

Last Updated : 04 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a list of tuples. The task is to get all the tuples that have all positive elements.

Examples:

Input : test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] 
Output : [(4, 5, 9)] 
Explanation : Extracted tuples with all positive elements.

Input : test_list = [(-4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] 
Output : [] 
Explanation : No tuple with all positive elements. 

Method #1 : Using list comprehension + all()

In this, all() is used to check for all the tuples, list comprehension helps in the iteration of tuples.

Step-by-step approach:

  • Initialize a list of tuples named test_list containing tuples of different lengths, with positive and negative integers.
  • Print the original list using the print() function with the string concatenation operator + to combine the string message with the list.
  • Use list comprehension to filter out the tuples containing only positive integers from the test_list. This is done using a conditional expression inside the comprehension that checks if all elements of the tuple are greater than or equal to zero.
  • Print the resulting list of positive tuples using the print() function with the string concatenation operator + to combine the string message with the list.
  • The program successfully filters out the tuples containing negative integers and returns only the tuples with positive integers.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Positive Tuples in List
# Using list comprehension + all()
 
# initializing list
test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# all() to check each element
res = [sub for sub in test_list if all(ele >= 0 for ele in sub)]
 
# printing result
print("Positive elements Tuples : " + str(res))


Output

The original list is : [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
Positive elements Tuples : [(4, 5, 9), (4, 6)]

Time complexity: O(n*m), where n is the number of tuples in the list and m is the number of elements in each tuple.
Auxiliary space: O(n), as a new list is created to store the positive tuples.

Method #2 : Using filter() + lambda + all()

In this, the task of filtration is performed using filter() and lambda function.

Python3




# Python3 code to demonstrate working of
# Positive Tuples in List
# Using filter() + lambda + all()
 
# initializing list
test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# all() to check each element
res = list(filter(lambda sub: all(ele >= 0 for ele in sub), test_list))
 
# printing result
print("Positive elements Tuples : " + str(res))


Output

The original list is : [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
Positive elements Tuples : [(4, 5, 9), (4, 6)]

Time complexity: O(n) where n is the number of elements in the list.
Auxiliary space: O(1) as the only extra space used is to store the result in a new list.

Method #3 : Using find(),map(),list() and join()

  1. Convert each tuple element to a string and then convert that tuple to a list.
  2. After that join elements of list using space.
  3. Now check if that joined list(which is a string) contains – sign in it.If – sign is found then tuple contains negative elements. 
  4. Ignore such tuples and add the other tuples to output list.

Python3




# Python3 code to demonstrate working of
# Positive Tuples in List
 
# initializing list
test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
 
# printing original list
print("The original list is : " + str(test_list))
 
res = []
for i in test_list:
    x = list(map(str, i))
    a = " ".join(x)
    if(a.find("-") == -1):
        res.append(i)
 
# printing result
print("Positive elements Tuples : " + str(res))


Output

The original list is : [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
Positive elements Tuples : [(4, 5, 9), (4, 6)]

Time complexity: O(n), where n is the number of tuples in the list.
Auxiliary space: O(n), as the result list is storing the positive tuples.

Method #4 : Using list(),map(),join() and startswith() methods

Python3




# Python3 code to demonstrate working of
# Positive Tuples in List
 
# initializing list
test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
 
# printing original list
print("The original list is : " + str(test_list))
 
res = []
for i in test_list:
    x = sorted(i)
    x = list(map(str, x))
    b = "".join(x)
    if(not b.startswith("-")):
        res.append(i)
 
# printing result
print("Positive elements Tuples : " + str(res))


Output

The original list is : [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
Positive elements Tuples : [(4, 5, 9), (4, 6)]

Time complexity: O(nlogn) where n is the length of the input list. 
Auxiliary space: O(n) where n is the length of the input list.

Method #5: By defining a function and using len() method

Python3




# Python3 code to demonstrate working of
# Positive Tuples in List
 
# initializing list
test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
 
# printing original list
print("The original list is : " + str(test_list))
res = []
 
 
def fun(x):
    c = 0
    for i in x:
        if(i > 0):
            c += 1
    if(c == len(x)):
        return True
    return False
 
 
for i in test_list:
    if(fun(i)):
        res.append(i)
 
# printing result
print("Positive elements Tuples : " + str(res))


Output

The original list is : [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
Positive elements Tuples : [(4, 5, 9), (4, 6)]

Time complexity: O(nm), where n is the length of the input list and m is the length of the tuples in the list.
Auxiliary space: O(k), where k is the length of the output list.

Method #6: Using list comprehension + not any()

In this, not any() is used to check for all the tuples, list comprehension helps in the iteration of tuples.

Python3




# Python3 code to demonstrate working of
# Positive Tuples in List
# Using list comprehension + all()
 
# initializing list
test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# not any() to check each element
res = [sub for sub in test_list if not any (ele < 0 for ele in sub)]
 
# printing result
print("Positive elements Tuples : " + str(res))


Output

The original list is : [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
Positive elements Tuples : [(4, 5, 9), (4, 6)]

Time Complexity:O(n)
Auxiliary Space :O(n)

Method #7: Without using built-in function

Python3




test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
result = []
# printing original list
print("The original list is : " + str(test_list))
for tup in test_list:
    positive = True
    for ele in tup:
        if ele < 0:
            positive = False
            break
    if positive:
        result.append(tup)
# printing result
print("Positive elements Tuples : " + str(result))
 
# This code contributed by Vinay Pinjala.


Output

The original list is : [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
Positive elements Tuples : [(4, 5, 9), (4, 6)]

Time Complexity:O(n)
Auxiliary Space :O(n)

Method #8: Using for loop and if condition to filter tuples with positive elements:

Approach :

  1. Initialize a list of tuples with various integers – this is done using the syntax test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)].
  2. Create an empty list called res to hold the tuples with positive elements – this is done using the syntax res = [].
  3. Loop through each tuple in the original list using a for loop – this is done using the syntax for tup in test_list:. The loop variable tup will take on the value of each tuple in the list, one at a time.
  4. Check if all elements in the tuple are positive using the all() function – this is done using the syntax if all(ele >= 0 for ele in tup):. The all() function returns True if all elements in the iterable passed to it satisfy the condition given in the generator expression, which in this case is ele >= 0. If any element in the tuple is less than 0, the condition is not satisfied and the if block is skipped.
  5. If all elements in the tuple are positive, add the tuple to the res list using the append() method – this is done using the syntax res.append(tup).
  6. After the loop is finished, print the resulting list of tuples with positive elements using the print() function and string concatenation – this is done using the syntax print(“Positive elements Tuples : ” + str(res)). The str() function is used to convert the res list to a string for concatenation with the string “Positive elements Tuples : “.

Python3




# initializing list
test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
 
# Create an empty list to hold the tuples with positive elements
res = []
 
# Loop through each tuple in the original list
for tup in test_list:
    # Check if all elements in the tuple are positive
    if all(ele >= 0 for ele in tup):
        # If so, add the tuple to the result list
        res.append(tup)
 
# Print the result
print("Positive elements Tuples : " + str(res))


Output

Positive elements Tuples : [(4, 5, 9), (4, 6)]

Time Complexity: O(n)
Auxiliary Space: O(n)

Using regular expressions:

We cam check if a tuple contains a negative number “-” in the string of tuple, we can use regular expressions (re) in Python. The approach is to convert the tuple to a string using str() and then search for a “-” using re.search(). If the string contains a “-“, it means that there is at least one negative number in the tuple.

Here’s the algorithm for the same:

Algorithm:

  • Initialize a list of tuples containing positive and negative integers.
  • Create an empty list to store tuples with only positive integers.
  • Loop through each tuple in the list of tuples.
  • Convert the tuple to a string using str().
  • Use re.search() to check if the string contains a “-“.
  • If the string does not contain a “-“, it means that the tuple contains only positive integers.
  • Append the tuple to the list of positive tuples.
  • Print the original list of tuples and the list of tuples with only positive integers.

Python3




import re
 
# initializing list of tuples containing positive and negative integers
test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
 
# empty list to store tuples with only positive integers
positive_list = []
 
# loop through each tuple in the list of tuples
for tup in test_list:
    # convert tuple to string using str()
    str_tup = str(tup)
    # use re.search() to check if string contains a "-"
    if not re.search('-', str_tup):
        # if string does not contain "-", append tuple to positive_list
        positive_list.append(tup)
 
# print original list of tuples and list of tuples with only positive integers
print("Original List: ", test_list)
print("Positive List: ", positive_list)


Output

Original List:  [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]
Positive List:  [(4, 5, 9), (4, 6)]

The time complexity of the given code is O(nm), where n is the length of the test_list and m is the maximum length of the tuple in the list.

This is because the code involves a loop through each tuple in the list, and for each tuple, it converts it to a string and searches for the “-” character using the re.search() function, which has a time complexity of O(m).

The space complexity of the given code is also O(nm), because it creates a new string representation of each tuple, which takes up O(m) space, and stores the positive tuples in a new list, which takes up O(nm) space in the worst case.



Similar Reads

Python program to find tuples which have all elements divisible by K from a list of tuples
Given a list of tuples. The task is to extract all tuples which have all elements divisible by K. Input : test_list = [(6, 24, 12), (60, 12, 6), (12, 18, 21)], K = 6 Output : [(6, 24, 12), (60, 12, 6)] Explanation : Both tuples have all elements multiple of 6. Input : test_list = [(6, 24, 12), (60, 10, 5), (12, 18, 21)], K = 5 Output : [(60, 10, 5)
7 min read
Python Program to find Sum of Negative, Positive Even and Positive Odd numbers in a List
Given a list. The task is to find the sum of Negative, Positive Even, and Positive Odd numbers present in the List. Examples: Input: -7 5 60 -34 1 Output: Sum of negative numbers is -41 Sum of even positive numbers is 60 Sum of odd positive numbers is 6 Input: 1 -1 50 -2 0 -3 Output: Sum of negative numbers is -6 Sum of even positive numbers is 50
7 min read
Python | Find the tuples containing the given element from a list of tuples
Given a list of tuples, the task is to find all those tuples containing the given element, say n. Examples: Input: n = 11, list = [(11, 22), (33, 55), (55, 77), (11, 44)] Output: [(11, 22), (11, 44)] Input: n = 3, list = [(14, 3),(23, 41),(33, 62),(1, 3),(3, 3)] Output: [(14, 3), (1, 3), (3, 3)] There are multiple ways we can find the tuples contai
6 min read
Python | Remove duplicate tuples from list of tuples
Given a list of tuples, Write a Python program to remove all the duplicated tuples from the given list. Examples: Input : [(1, 2), (5, 7), (3, 6), (1, 2)] Output : [(1, 2), (5, 7), (3, 6)] Input : [('a', 'z'), ('a', 'x'), ('z', 'x'), ('a', 'x'), ('z', 'x')] Output : [('a', 'z'), ('a', 'x'), ('z', 'x')] Method #1 : List comprehension This is a naive
5 min read
Python | Remove tuples from list of tuples if greater than n
Given a list of a tuple, the task is to remove all the tuples from list, if it's greater than n (say 100). Let's discuss a few methods for the same. Method #1: Using lambda STEPS: Initialize a list of tuples: ini_tuple = [('b', 100), ('c', 200), ('c', 45), ('d', 876), ('e', 75)]Print the initial list: print("intial_list", str(ini_tuple))Define the
6 min read
Python | Remove tuples having duplicate first value from given list of tuples
Given a list of tuples, the task is to remove all tuples having duplicate first values from the given list of tuples. Examples: Input: [(12.121, 'Tuple1'), (12.121, 'Tuple2'), (12.121, 'Tuple3'), (923232.2323, 'Tuple4')] Output: [(12.121, 'Tuple1'), (923232.2323, 'Tuple4')]Input: [('Tuple1', 121), ('Tuple2', 125), ('Tuple1', 135), ('Tuple4', 478)]
7 min read
Python | Count tuples occurrence in list of tuples
Many a time while developing web and desktop products in Python, we use nested lists and have several queries about how to find the count of unique tuples. Let us see how to get the count of unique tuples in the given list of tuples. Below are some ways to achieve the above task. Method #1: Using Iteration C/C++ Code # Python code to count unique #
5 min read
Python | Combining tuples in list of tuples
Sometimes, we might have to perform certain problems related to tuples in which we need to segregate the tuple elements to combine with each element of complex tuple element( such as list ). This can have application in situations we need to combine values to form a whole. Let's discuss certain ways in which this can be performed. Method #1: Using
7 min read
Python | Convert string tuples to list tuples
Sometimes, while working with Python we can have a problem in which we have a list of records in form of tuples in stringified form and we desire to convert them to a list of tuples. This kind of problem can have its occurrence in the data science domain. Let's discuss certain ways in which this task can be performed. Method 1 (Using eval() + list
4 min read
Python - Filter all uppercase characters Tuples from given list of tuples
Given a Tuple list, filter tuples that contain all uppercase characters. Input : test_list = [("GFG", "IS", "BEST"), ("GFg", "AVERAGE"), ("GfG", ), ("Gfg", "CS")] Output : [('GFG', 'IS', 'BEST')] Explanation : Only 1 tuple has all uppercase Strings. Input : test_list = [("GFG", "iS", "BEST"), ("GFg", "AVERAGE"), ("GfG", ), ("Gfg", "CS")] Output : [
8 min read
Generating a Set of Tuples from a List of Tuples in Python
Python provides a versatile set of tools for manipulating data structures, and when it comes to working with tuples, developers often need to extract unique elements or create a set of tuples from a given list. In this article, we will explore some simple and commonly used methods to generate a set of tuples from a list of tuples in Python. Generat
4 min read
Python - Add list elements to tuples list
Sometimes, while working with Python tuples, we can have a problem in which we need to add all the elements of a particular list to all tuples of a list. This kind of problem can come in domains such as web development and day-day programming. Let's discuss certain ways in which this task can be done. Input : test_list = [(5, 6), (2, 4), (5, 7), (2
6 min read
Python | How to Concatenate tuples to nested tuples
Sometimes, while working with tuples, we can have a problem in which we need to convert individual records into a nested collection yet remaining as separate element. Usual addition of tuples, generally adds the contents and hence flattens the resultant container, this is usually undesired. Let's discuss certain ways in which this problem is solved
6 min read
Python | Convert list of tuples to list of list
This is a quite simple problem but can have a good amount of application due to certain constraints of Python language. Because tuples are immutable, they are not easy to process whereas lists are always a better option while processing. Let's discuss certain ways in which we can convert a list of tuples to list of list. Method #1: Using list compr
8 min read
Python program to Convert a elements in a list of Tuples to Float
Given a Tuple list, convert all possible convertible elements to float. Input : test_list = [("3", "Gfg"), ("1", "26.45")] Output : [(3.0, 'Gfg'), (1.0, 26.45)] Explanation : Numerical strings converted to floats. Input : test_list = [("3", "Gfg")] Output : [(3.0, 'Gfg')] Explanation : Numerical strings converted to floats. Method #1 : Using loop +
5 min read
Python | Find top K frequent elements from a list of tuples
Given a list of tuples with word as first element and its frequency as second element, the task is to find top k frequent element. Below are some ways to above achieve the above task. Method #1: Using defaultdict C/C++ Code # Python code to find top 'k' frequent element # Importing import collections from operator import itemgetter from itertools i
5 min read
Python program to create a list of tuples from given list having number and its cube in each tuple
Given a list of numbers of list, write a Python program to create a list of tuples having first element as the number and second element as the cube of the number. Example: Input: list = [1, 2, 3] Output: [(1, 1), (2, 8), (3, 27)] Input: list = [9, 5, 6] Output: [(9, 729), (5, 125), (6, 216)] Method #1 : Using pow() function.We can use list compreh
5 min read
Python Program to Convert Tuple Value List to List of Tuples
Given a dictionary with values as a tuple list, convert it to a key-mapped list of tuples. Input : test_dict = {'Gfg' : [(5, ), (6, )], 'is' : [(5, )], 'best' :[(7, )]} Output : [('Gfg', 5), ('Gfg', 6), ('is', 5), ('best', 7)] Explanation : Keys grouped with values.Convert Tuple Value List to List of Tuples Using loop + * operator + items() This is
8 min read
Python | Get positive elements from given list of lists
Given a list of list, the task is to get only positive element from given list. Below are some ways to solve the above problem. Method #1: Using Iteration C/C++ Code # Python code to get positive # element from list of list # List Initialisation Input = [[10, -11, 222], [42, -222, -412, 99, -87]] Output = [] # Using iteration for elem in Input: tem
5 min read
Python - Calculate the percentage of positive elements of the list
Given a list, compute the percentage of positive elements in the list. Input : test_list = [4, 6, -2, 3, -8, -9, -1, 8, 9, 1] Output : 60.0 Explanation : 6/10 elements are positive. Input : test_list = [-4, 6, -2, 3, -8, -9, -1, 8, 9, 1] Output : 50.0 Explanation : 5/10 elements are positive. Method #1 : Using len() + list comprehension In this, we
4 min read
Python program to count positive and negative numbers in a list
Given a list of numbers, write a Python program to count positive and negative numbers in a List. Example: Input: list1 = [2, -7, 5, -64, -14] Output: pos = 2, neg = 3 Input: list2 = [-12, 14, 95, 3] Output: pos = 3, neg = 1 Example #1: Count positive and negative numbers from the given list using for loop Iterate each element in the list using for
6 min read
Python program to print positive numbers in a list
Given a list of numbers, write a Python program to print all positive numbers in given list. Example: Input: list1 = [12, -7, 5, 64, -14]Output: 12, 5, 64Input: list2 = [12, 14, -95, 3]Output: [12, 14, 3]Example #1: Print all positive numbers from given list using for loop Iterate each element in the list using for loop and check if number is great
4 min read
Python | Swap tuple elements in list of tuples
While doing competitive programming, one can come across a question in which one requires to work with 2D plane and work with coordinates. One such subproblem can be swapping x, y coordinate elements. Let's discuss certain ways in which this problem can be solved using tuple element swapping. Method #1 : Using list comprehension This is just a brut
4 min read
Python | Convert list elements to bi-tuples
Sometimes, while working with Python lists, we can have a subproblem in which we need to tie a particular element with each of the list elements. This task can have its utility in the web development domain while working with queries and filters. Let's discuss ways to solve this problem. Method 1: Using zip() + repeat() This problem can be solved u
6 min read
Python - Change the signs of elements of tuples in a list
Given a dual Tuple list, the task is to write a python program to convert second element to negative magnitude of each tuple and first element to positive magnitude of each tuple. Input : test_list = [(3, -1), (-4, -3), (1, 3), (-2, 5), (-4, 2), (-9, -3)] Output : [(3, -1), (4, -3), (1, -3), (2, -5), (4, -2), (9, -3)] Explanation : All the first el
3 min read
Python | Convert list of tuples into list
Given a list of tuples, write a Python program to convert it into a list. Example Input: [(11, 20), (13, 40), (55, 16)] Output:[11, 20, 13, 40, 55, 16] Input: [('Geeks', 2), ('For', 4), ('geek', '6')] Output: ['Geeks', 2, 'For', 4, 'geek', '6'] Convert List of Tuples to List of Lists in Python MethodsConvert lists of tuples into a list using LoopTh
5 min read
Python | Convert list of tuples to list of strings
The interconversion between datatypes is a quite useful utility and many articles have been written to perform the same. This article discusses the interconversion between a tuple of characters to individual strings. This kind of interconversion is useful in Machine Learning in which we need to give the input to train the model in a specific format
4 min read
Python | Update a list of tuples using another list
Given two list of tuples, write a Python program to update 'list1' according to the 'list2' and return an updated list. Examples: Input : list1 = [('x', 0), ('y', 5)] list2 = [('x', 100), ('y', 200)] Output : [('x', 100), ('y', 200)] Input : list1 = [('a', 0), ('b', 0), ('c', 0)] list2 = [('a', 1), ('b', 2)] Output :[('a', 1), ('b', 2), ('c', 0)] A
4 min read
Convert list of strings to list of tuples in Python
Sometimes we deal with different types of data types and we require to inter-convert from one data type to another hence interconversion is always a useful tool to have knowledge. This article deals with the converse case. Let's discuss certain ways in which this can be done in Python. Method 1: Convert a list of strings to a list of tuples using t
5 min read
Python | Find Dissimilar Elements in Tuples
Sometimes, while working with tuples, we can have a problem in which we need dissimilar features of two records. This type of application can come in Data Science domain. Let's discuss certain ways in which this problem can be solved. Method #1 : Using set() + "^" operator This task can be performed using symmetric difference functionality offered
8 min read