Open In App

Python program to find tuples which have all elements divisible by K from a list of tuples

Last Updated : 21 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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)] 
Explanation : Multiple of 5 tuples extracted. 

Method #1 : Using list comprehension + all()

In this, we test for all elements to be K multiple using all() for filtering purpose, and list comprehension is used for the iteration of all tuples.

Python3




# Python3 code to demonstrate working of
# K Multiple Elements Tuples
# Using list comprehension + all()
 
# initializing list
test_list = [(6, 24, 12), (7, 9, 6), (12, 18, 21)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 6
 
# all() used to filter elements
res = [sub for sub in test_list if all(ele % K == 0 for ele in sub)]
 
# printing result
print("K Multiple elements tuples : " + str(res))


Output

The original list is : [(6, 24, 12), (7, 9, 6), (12, 18, 21)]
K Multiple elements tuples : [(6, 24, 12)]

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

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

Step-by-step approach:

  • In this, perform task of filtering using filter() + lambda, and logic provided by all().
  • The program initializes a list called test_list containing three tuples, each with three integer values.
  • The program prints the original list by concatenating a string with the string representation of test_list.
  • The program initializes an integer variable K.
  • The program uses the filter() function to filter the tuples in test_list based on the condition that all elements in the tuple are divisible by K.
  • The program defines a lambda function that takes a sublist (tuple) as an argument and returns True if all elements in the sublist are divisible by K.
  • The filter() function iterates through each tuple in test_list, applies the lambda function to each tuple, and keeps the tuples that satisfy the condition.
  • The res variable stores the filtered tuples in a list.
  • Prints the result by concatenating a string with the string representation of res

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# K Multiple Elements Tuples
# Using filter() + lambda + all()
 
# initializing list
test_list = [(6, 24, 12), (7, 9, 6), (12, 18, 21)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 6
 
# filter() + lambda for filter operation
res = list(filter(lambda sub: all(ele % K == 0 for ele in sub), test_list))
 
# printing result
print("K Multiple elements tuples : " + str(res))


Output

The original list is : [(6, 24, 12), (7, 9, 6), (12, 18, 21)]
K Multiple elements tuples : [(6, 24, 12)]

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

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

In this, we test for all elements to be K multiple using not any () for filtering purpose, and list comprehension is used for iteration of all tuples.

Python3




# Initialize list
test_list = [(6, 24, 12), (7, 9, 6), (12, 18, 21)]
 
# Initialize K
K = 6
 
# list comprehension
result = [tup for tup in test_list if not any(x % K != 0 for x in tup)]
# printing original list
print("The original list is : " + str(test_list))
# Print the list of tuples whose elements are multiples of K
print("K Multiple elements tuples : " + str(result))


Output

The original list is : [(6, 24, 12), (7, 9, 6), (12, 18, 21)]
K Multiple elements tuples : [(6, 24, 12)]

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), where n is the number of tuples in the list.

Method #4: Using for loops

Python3




# Python3 code to demonstrate working of
# K Multiple Elements Tuples
 
# initializing list
test_list = [(6, 24, 12), (7, 9, 6), (12, 18, 21)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 6
 
res = []
for i in test_list:
    c=0
    for j in i:
        if(j%K==0):
            c+=1
    if(c==len(i)):
        res.append(i)
 
# printing result
print("K Multiple elements tuples : " + str(res))


Output

The original list is : [(6, 24, 12), (7, 9, 6), (12, 18, 21)]
K Multiple elements tuples : [(6, 24, 12)]

Time Complexity: O(n*n), where n is the number of tuples in the list “test_list”.
Auxiliary Space: O(m), where m is the number of tuples in “res”.

Method #5: Using Recursive method.

Python3




# Python3 code to demonstrate working of
# K Multiple Elements Tuples
 
def even_tuple(lst,K,newlst=[],start=0):
  if start==len(lst):
    return newlst
  for i in lst[start]:
    if i%K!=0:
      return even_tuple(lst,K,newlst,start+1)
  else:
    newlst.append(lst[start])
  return even_tuple(lst,K,newlst,start+1)
# initializing list
test_list = [(6, 24, 12), (7, 9, 6), (12, 18, 21)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 6
 
res = even_tuple(test_list,K)
 
# printing result
print("K Multiple elements tuples : " + str(res))
#this code contributed by tvsk


Output

The original list is : [(6, 24, 12), (7, 9, 6), (12, 18, 21)]
K Multiple elements tuples : [(6, 24, 12)]

Time Complexity: O(n*m), where n is length of the list and m is length of each tuple.
Auxiliary Space: O(n)

Method 6: Using the filter() function, without using lambda and all()

The implementation defines a function is_multiple_of_K() that checks if all elements in a tuple are multiples of K, and then applies the filter() function to keep only the tuples that satisfy this condition. Finally, it converts the filtered result into a list and prints it.

Python3




test_list = [(6, 24, 12), (7, 9, 6), (12, 18, 21)]
K = 6
 
# define a function to check if all elements in a tuple are multiples of K
def is_multiple_of_K(tup):
    return all(ele % K == 0 for ele in tup)
 
# use filter() to keep only tuples that satisfy the condition
res = list(filter(is_multiple_of_K, test_list))
 
# printing original list
print("The original list is : " + str(test_list))
 
print("K Multiple elements tuples : " + str(res))


Output

The original list is : [(6, 24, 12), (7, 9, 6), (12, 18, 21)]
K Multiple elements tuples : [(6, 24, 12)]

Time complexity: O(n), where n is the number of tuples in the test_list.
Auxiliary space: O(1), as the function only uses a constant amount of space to store the K value.

Method #7: Using numpy array and np.all()

Python3




import numpy as np
 
# initializing the list
test_list = [(6, 24, 12), (7, 9, 6), (12, 18, 21)]
 
# printing the original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 6
 
# converting the list to a numpy array
arr = np.array(test_list)
 
# using np.all() to filter elements
res = arr[np.all(arr % K == 0, axis=1)]
 
# printing the result
print("K Multiple elements tuples : " + str(res))


Output: 

K Multiple elements tuples : [[ 6 24 12]]

Time Complexity: O(nm), where n is the number of tuples in the input list, and m is the number of elements in each tuple.
Auxiliary Space: O(nm)



Similar Reads

Python program to find Tuples with positive elements in List of tuples
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 wit
10 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
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 - Check if all tuples have element difference less than K
Given a Tuple list, check if each tuple has a difference less than K. Input : test_list = [(3, 4), (1, 2), (7, 8), (9, 13)], K = 2 Output : False Explanation : 13 - 9 = 4 > 2. Input : test_list = [(3, 4), (1, 2), (7, 8)], K = 2Output : True Explanation : All have abs. diff 1 < 2. Method #1 : Using loop In this, we keep a boolean variable and
7 min read
Python Program to Find XOR of array elements which are divisible by given number
Given an array arr[] containing integers of size N and a number k, the task is to find the XOR of array elements that are divisible by a given number k in Python. Examples: Input: arr[] = {3, 9, 16, 12, 13, 15} , k = 3 Output: 25 Explanation: Only 3,9,12,15 are divisible by 3, XOR = 3^9^12^15 = 9 Input: arr[] = { 3, 9, 12, 13, 15, 2 , 6, 18 } , k=2
5 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
three90RightbarBannerImg