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))
OutputThe 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))
OutputThe 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()
- Convert each tuple element to a string and then convert that tuple to a list.
- After that join elements of list using space.
- Now check if that joined list(which is a string) contains - sign in it.If - sign is found then tuple contains negative elements.
- 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))
OutputThe 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))
OutputThe 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))
OutputThe 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))
OutputThe 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.
OutputThe 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 :
- 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)].
- Create an empty list called res to hold the tuples with positive elements - this is done using the syntax res = [].
- 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.
- 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.
- 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).
- 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))
OutputPositive 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)
OutputOriginal 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,
7 min read
Python Program to find tuple indices from other tuple list
Given Tuples list and search list consisting of tuples to search, our task is to write a Python Program to extract indices of matching tuples. Input : test_list = [(4, 5), (7, 6), (1, 0), (3, 4)], search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]Output : [3, 1]Explanation : (3, 4) from search list is fo
8 min read
Python | Check if element is present in tuple of tuples
Sometimes the data that we use is in the form of tuples and often we need to look into the nested tuples as well. The common problem that this can solve is looking for missing data or na value in data preprocessing. Let's discuss certain ways in which this can be performed. Method #1: Using any() an
4 min read
Python program to find the Decreasing point in List
Given a list, get the index of element where the list shows the first negative trend, i.e first point where the next element < current element. If not found return -1. Input : test_list = [3, 6, 8, 9, 12, 5, 18, 1] Output : 4 Explanation : At 12 -> 5, first decreasing point occurs. Input : tes
4 min read
Python program to find all possible pairs with given sum
Given a list of integers and an integer variable K, write a Python program to find all pairs in the list with given sum K. Examples: Input : lst =[1, 5, 3, 7, 9] K = 12 Output : [(5, 7), (3, 9)] Input : lst = [2, 1, 5, 7, -1, 4] K = 6 Output : [(2, 4), (1, 5), (7, -1)] Method #1: Pythonic Naive This
7 min read
Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]
8 min read
Python | Program to count duplicates in a list of tuples
Given a list of tuples, write a Python program to check if an element of the list has duplicates. If duplicates exist, print the number of occurrences of each duplicate tuple, otherwise print "No Duplicates". Examples: Input : [('a', 'e'), ('b', 'x'), ('b', 'x'), ('a', 'e'), ('b', 'x')] Output : ('a
6 min read
Python Program to extracts elements from the list with digits in increasing order
Given a List of elements, extract all elements which have digits that are increasing in order. Input : test_list = [1234, 7373, 3643, 3527, 148, 49] Output : [1234, 148, 49] Explanation : All elements have increasing digits.Input : test_list = [12341, 7373, 3643, 3527, 1481, 491] Output : [] Explana
5 min read
Output of python program | Set 13(Lists and Tuples)
Prerequisite: Lists and Tuples1) What is the output of the following program? PYTHON List = [True, 50, 10] List.insert(2, 5) print(List, "Sum is: ", sum(List)) a) [True, 50, 10, 5] Sum is: 66 b) [True, 50, 5, 10] Sum is: 65 c) TypeError: unsupported operand type(s) for +: 'int' and 'str' d) [True, 5
3 min read
Python program to fetch the indices of true values in a Boolean list
Given a list of only boolean values, write a Python program to fetch all the indices with True values from given list. Let's see certain ways to do this task. Method #1: Using itertools [Pythonic way] itertools.compress() function checks for all the elements in list and returns the list of indices w
5 min read