Description
stringlengths
9
105
Link
stringlengths
45
135
Code
stringlengths
10
26.8k
Test_Case
stringlengths
9
202
Merge
stringlengths
63
27k
Python - Remove nested records from tuple
https://www.geeksforgeeks.org/python-remove-nested-records-from-tuple/
# Python3 code to demonstrate working of # Remove nested records # initialize tuple test_tup = (1, 5, 7, (4, 6), 10) # printing original tuple print("The original tuple : " + str(test_tup)) # Remove nested records res = list(filter(lambda x: not isinstance(x, tuple), test_tup)) # printing result print("Elements after removal of nested records : " + str(res))
#Output : The original tuple : (1, 5, 7, (4, 6), 10)
Python - Remove nested records from tuple # Python3 code to demonstrate working of # Remove nested records # initialize tuple test_tup = (1, 5, 7, (4, 6), 10) # printing original tuple print("The original tuple : " + str(test_tup)) # Remove nested records res = list(filter(lambda x: not isinstance(x, tuple), test_tup)) # printing result print("Elements after removal of nested records : " + str(res)) #Output : The original tuple : (1, 5, 7, (4, 6), 10) [END]
Python - Remove nested records from tuple
https://www.geeksforgeeks.org/python-remove-nested-records-from-tuple/
# Python3 code to demonstrate working of # Remove nested records # initialize tuple test_tup = (1, 5, 7, (4, 6), 10) # printing original tuple print("The original tuple : " + str(test_tup)) # Remove nested records res = [x for x in test_tup if not isinstance(x, tuple)] # printing result print("Elements after removal of nested records : " + str(res)) # This code is contributed by Edula Vinay Kumar Reddy
#Output : The original tuple : (1, 5, 7, (4, 6), 10)
Python - Remove nested records from tuple # Python3 code to demonstrate working of # Remove nested records # initialize tuple test_tup = (1, 5, 7, (4, 6), 10) # printing original tuple print("The original tuple : " + str(test_tup)) # Remove nested records res = [x for x in test_tup if not isinstance(x, tuple)] # printing result print("Elements after removal of nested records : " + str(res)) # This code is contributed by Edula Vinay Kumar Reddy #Output : The original tuple : (1, 5, 7, (4, 6), 10) [END]
Python - Remove nested records from tuple
https://www.geeksforgeeks.org/python-remove-nested-records-from-tuple/
from functools import reduce test_tup = (1, 5, 7, (4, 6), 10) # printing original tuple print("The original tuple : " + str(test_tup)) res = reduce( lambda acc, x: acc + (x,) if not isinstance(x, tuple) else acc, test_tup, () ) print(res) # This code is contributed by Jyothi pinjala.
#Output : The original tuple : (1, 5, 7, (4, 6), 10)
Python - Remove nested records from tuple from functools import reduce test_tup = (1, 5, 7, (4, 6), 10) # printing original tuple print("The original tuple : " + str(test_tup)) res = reduce( lambda acc, x: acc + (x,) if not isinstance(x, tuple) else acc, test_tup, () ) print(res) # This code is contributed by Jyothi pinjala. #Output : The original tuple : (1, 5, 7, (4, 6), 10) [END]
Python - Remove nested records from tuple
https://www.geeksforgeeks.org/python-remove-nested-records-from-tuple/
import itertools test_tup = (1, 5, 7, (4, 6), 10) print("The original tuple: " + str(test_tup)) res = tuple( itertools.chain(*([x] if not isinstance(x, tuple) else x for x in test_tup)) ) print(res)
#Output : The original tuple : (1, 5, 7, (4, 6), 10)
Python - Remove nested records from tuple import itertools test_tup = (1, 5, 7, (4, 6), 10) print("The original tuple: " + str(test_tup)) res = tuple( itertools.chain(*([x] if not isinstance(x, tuple) else x for x in test_tup)) ) print(res) #Output : The original tuple : (1, 5, 7, (4, 6), 10) [END]
Python - Remove nested records from tuple
https://www.geeksforgeeks.org/python-remove-nested-records-from-tuple/
def flatten_tuple(tup): """ Recursively flatten a tuple of any depth into a single tuple. Args: tup: A tuple to be flattened. Returns: A flattened tuple. """ result = [] for elem in tup: if not isinstance(elem, tuple): result.append(elem) else: result.extend(flatten_tuple(elem)) return tuple(result) # Driver code to test the function test_tup = (1, 5, 7, (4, 6), 10) print("The original tuple: " + str(test_tup)) # Call the function to flatten the tuple res = flatten_tuple(test_tup) # Print the flattened tuple print(res)
#Output : The original tuple : (1, 5, 7, (4, 6), 10)
Python - Remove nested records from tuple def flatten_tuple(tup): """ Recursively flatten a tuple of any depth into a single tuple. Args: tup: A tuple to be flattened. Returns: A flattened tuple. """ result = [] for elem in tup: if not isinstance(elem, tuple): result.append(elem) else: result.extend(flatten_tuple(elem)) return tuple(result) # Driver code to test the function test_tup = (1, 5, 7, (4, 6), 10) print("The original tuple: " + str(test_tup)) # Call the function to flatten the tuple res = flatten_tuple(test_tup) # Print the flattened tuple print(res) #Output : The original tuple : (1, 5, 7, (4, 6), 10) [END]
Python - Elements Frequency in StringMixed Nested tuple
https://www.geeksforgeeks.org/python-elements-frequency-in-mixed-nested-tuple/
# Python3 code to demonstrate working of # Elements Frequency in Mixed Nested Tuple # Using recursion + loop # helper_fnc def flatten(test_tuple): for tup in test_tuple: if isinstance(tup, tuple): yield from flatten(tup) else: yield tup # initializing tuple test_tuple = (5, 6, (5, 6), 7, (8, 9), 9) # printing original tuple print("The original tuple : " + str(test_tuple)) # Elements Frequency in Mixed Nested Tuple # Using recursion + loop res = {} for ele in flatten(test_tuple): if ele not in res: res[ele] = 0 res[ele] += 1 # printing result print("The elements frequency : " + str(res))
#Output : The original tuple : (5, 6, (5, 6), 7, (8, 9), 9)
Python - Elements Frequency in StringMixed Nested tuple # Python3 code to demonstrate working of # Elements Frequency in Mixed Nested Tuple # Using recursion + loop # helper_fnc def flatten(test_tuple): for tup in test_tuple: if isinstance(tup, tuple): yield from flatten(tup) else: yield tup # initializing tuple test_tuple = (5, 6, (5, 6), 7, (8, 9), 9) # printing original tuple print("The original tuple : " + str(test_tuple)) # Elements Frequency in Mixed Nested Tuple # Using recursion + loop res = {} for ele in flatten(test_tuple): if ele not in res: res[ele] = 0 res[ele] += 1 # printing result print("The elements frequency : " + str(res)) #Output : The original tuple : (5, 6, (5, 6), 7, (8, 9), 9) [END]
Python - Elements Frequency in StringMixed Nested tuple
https://www.geeksforgeeks.org/python-elements-frequency-in-mixed-nested-tuple/
# Python3 code to demonstrate working of # Elements Frequency in Mixed Nested Tuple # Using recursion + Counter() from collections import Counter # helper_fnc def flatten(test_tuple): for tup in test_tuple: if isinstance(tup, tuple): yield from flatten(tup) else: yield tup # initializing tuple test_tuple = (5, 6, (5, 6), 7, (8, 9), 9) # printing original tuple print("The original tuple : " + str(test_tuple)) # Elements Frequency in Mixed Nested Tuple # Using recursion + Counter() res = dict(Counter(flatten(test_tuple))) # printing result print("The elements frequency : " + str(res))
#Output : The original tuple : (5, 6, (5, 6), 7, (8, 9), 9)
Python - Elements Frequency in StringMixed Nested tuple # Python3 code to demonstrate working of # Elements Frequency in Mixed Nested Tuple # Using recursion + Counter() from collections import Counter # helper_fnc def flatten(test_tuple): for tup in test_tuple: if isinstance(tup, tuple): yield from flatten(tup) else: yield tup # initializing tuple test_tuple = (5, 6, (5, 6), 7, (8, 9), 9) # printing original tuple print("The original tuple : " + str(test_tuple)) # Elements Frequency in Mixed Nested Tuple # Using recursion + Counter() res = dict(Counter(flatten(test_tuple))) # printing result print("The elements frequency : " + str(res)) #Output : The original tuple : (5, 6, (5, 6), 7, (8, 9), 9) [END]
Python - Elements Frequency in StringMixed Nested tuple
https://www.geeksforgeeks.org/python-elements-frequency-in-mixed-nested-tuple/
# Python3 code to demonstrate working of # Elements Frequency in Mixed Nested Tuple # Initializing tuple test_tuple = (5, 6, (5, 6), 7, (8, 9), 9) # Printing original tuple print("The original tuple : " + str(test_tuple)) # Elements Frequency in Mixed Nested Tuple x = [] for i in test_tuple: if type(i) is tuple: x.extend(list(i)) else: x.append(i) res = dict() a = list(set(x)) for i in a: res[i] = x.count(i) # Printing result print("The elements frequency : " + str(res))
#Output : The original tuple : (5, 6, (5, 6), 7, (8, 9), 9)
Python - Elements Frequency in StringMixed Nested tuple # Python3 code to demonstrate working of # Elements Frequency in Mixed Nested Tuple # Initializing tuple test_tuple = (5, 6, (5, 6), 7, (8, 9), 9) # Printing original tuple print("The original tuple : " + str(test_tuple)) # Elements Frequency in Mixed Nested Tuple x = [] for i in test_tuple: if type(i) is tuple: x.extend(list(i)) else: x.append(i) res = dict() a = list(set(x)) for i in a: res[i] = x.count(i) # Printing result print("The elements frequency : " + str(res)) #Output : The original tuple : (5, 6, (5, 6), 7, (8, 9), 9) [END]
Python - Elements Frequency in StringMixed Nested tuple
https://www.geeksforgeeks.org/python-elements-frequency-in-mixed-nested-tuple/
# Python3 code to demonstrate working of # Elements Frequency in Mixed Nested Tuple import operator as op # Initializing tuple test_tuple = (5, 6, (5, 6), 7, (8, 9), 9) # Printing original tuple print("The original tuple : " + str(test_tuple)) # Elements Frequency in Mixed Nested Tuple x = [] for i in test_tuple: if type(i) is tuple: x.extend(list(i)) else: x.append(i) res = dict() a = list(set(x)) for i in a: res[i] = op.countOf(x, i) # Printing result print("The elements frequency : " + str(res))
#Output : The original tuple : (5, 6, (5, 6), 7, (8, 9), 9)
Python - Elements Frequency in StringMixed Nested tuple # Python3 code to demonstrate working of # Elements Frequency in Mixed Nested Tuple import operator as op # Initializing tuple test_tuple = (5, 6, (5, 6), 7, (8, 9), 9) # Printing original tuple print("The original tuple : " + str(test_tuple)) # Elements Frequency in Mixed Nested Tuple x = [] for i in test_tuple: if type(i) is tuple: x.extend(list(i)) else: x.append(i) res = dict() a = list(set(x)) for i in a: res[i] = op.countOf(x, i) # Printing result print("The elements frequency : " + str(res)) #Output : The original tuple : (5, 6, (5, 6), 7, (8, 9), 9) [END]
Python - Elements Frequency in StringMixed Nested tuple
https://www.geeksforgeeks.org/python-elements-frequency-in-mixed-nested-tuple/
from collections import defaultdict def count_elements(t): freq = defaultdict(int) for item in t: if isinstance(item, int): freq[item] += 1 elif isinstance(item, tuple): sub_freq = count_elements(item) for k, v in sub_freq.items(): freq[k] += v return freq # Example usage test_tuple = (5, 6, (5, 6), 7, (8, 9), 9) # Printing original tuple print("The original tuple : " + str(test_tuple)) result = count_elements(test_tuple) print("The elements frequency : " + str(result)) # This code is contributed by Vinay Pinjala.
#Output : The original tuple : (5, 6, (5, 6), 7, (8, 9), 9)
Python - Elements Frequency in StringMixed Nested tuple from collections import defaultdict def count_elements(t): freq = defaultdict(int) for item in t: if isinstance(item, int): freq[item] += 1 elif isinstance(item, tuple): sub_freq = count_elements(item) for k, v in sub_freq.items(): freq[k] += v return freq # Example usage test_tuple = (5, 6, (5, 6), 7, (8, 9), 9) # Printing original tuple print("The original tuple : " + str(test_tuple)) result = count_elements(test_tuple) print("The elements frequency : " + str(result)) # This code is contributed by Vinay Pinjala. #Output : The original tuple : (5, 6, (5, 6), 7, (8, 9), 9) [END]
Python - Elements Frequency in StringMixed Nested tuple
https://www.geeksforgeeks.org/python-elements-frequency-in-mixed-nested-tuple/
def count_elements(t): freq = {} for item in t: if isinstance(item, int): if item not in freq: freq[item] = 0 freq[item] += 1 elif isinstance(item, tuple): for subitem in item: if isinstance(subitem, int): if subitem not in freq: freq[subitem] = 0 freq[subitem] += 1 return freq # Example usage test_tuple = (5, 6, (5, 6), 7, (8, 9), 9) # Printing original tuple print("The original tuple : " + str(test_tuple)) result = count_elements(test_tuple) print("The elements frequency : " + str(result)) # This code is contributed by tvsk.
#Output : The original tuple : (5, 6, (5, 6), 7, (8, 9), 9)
Python - Elements Frequency in StringMixed Nested tuple def count_elements(t): freq = {} for item in t: if isinstance(item, int): if item not in freq: freq[item] = 0 freq[item] += 1 elif isinstance(item, tuple): for subitem in item: if isinstance(subitem, int): if subitem not in freq: freq[subitem] = 0 freq[subitem] += 1 return freq # Example usage test_tuple = (5, 6, (5, 6), 7, (8, 9), 9) # Printing original tuple print("The original tuple : " + str(test_tuple)) result = count_elements(test_tuple) print("The elements frequency : " + str(result)) # This code is contributed by tvsk. #Output : The original tuple : (5, 6, (5, 6), 7, (8, 9), 9) [END]
Python Program to get unique elements in nested tuple
https://www.geeksforgeeks.org/python-how-to-get-unique-elements-in-nested-tuple/
# Python3 code to demonstrate working of # Unique elements in nested tuple # Using nested loop + set() # initialize list test_list = [(3, 4, 5), (4, 5, 7), (1, 4)] # printing original list print("The original list : " + str(test_list)) # Unique elements in nested tuple # Using nested loop + set() res = [] temp = set() for inner in test_list: for ele in inner: if not ele in temp: temp.add(ele) res.append(ele) # printing result print("Unique elements in nested tuples are : " + str(res))
#Output : The original list : [(3, 4, 5), (4, 5, 7), (1, 4)]
Python Program to get unique elements in nested tuple # Python3 code to demonstrate working of # Unique elements in nested tuple # Using nested loop + set() # initialize list test_list = [(3, 4, 5), (4, 5, 7), (1, 4)] # printing original list print("The original list : " + str(test_list)) # Unique elements in nested tuple # Using nested loop + set() res = [] temp = set() for inner in test_list: for ele in inner: if not ele in temp: temp.add(ele) res.append(ele) # printing result print("Unique elements in nested tuples are : " + str(res)) #Output : The original list : [(3, 4, 5), (4, 5, 7), (1, 4)] [END]
Python Program to get unique elements in nested tuple
https://www.geeksforgeeks.org/python-how-to-get-unique-elements-in-nested-tuple/
# Python3 code to demonstrate working of # Unique elements in nested tuple # Using from_iterable() + set() from itertools import chain # initialize list test_list = [(3, 4, 5), (4, 5, 7), (1, 4)] # printing original list print("The original list : " + str(test_list)) # Unique elements in nested tuple # Using from_iterable() + set() res = list(set(chain.from_iterable(test_list))) # printing result print("Unique elements in nested tuples are : " + str(res))
#Output : The original list : [(3, 4, 5), (4, 5, 7), (1, 4)]
Python Program to get unique elements in nested tuple # Python3 code to demonstrate working of # Unique elements in nested tuple # Using from_iterable() + set() from itertools import chain # initialize list test_list = [(3, 4, 5), (4, 5, 7), (1, 4)] # printing original list print("The original list : " + str(test_list)) # Unique elements in nested tuple # Using from_iterable() + set() res = list(set(chain.from_iterable(test_list))) # printing result print("Unique elements in nested tuples are : " + str(res)) #Output : The original list : [(3, 4, 5), (4, 5, 7), (1, 4)] [END]
Python Program to get unique elements in nested tuple
https://www.geeksforgeeks.org/python-how-to-get-unique-elements-in-nested-tuple/
# Python3 code to demonstrate working of # Unique elements in nested tuple # initialize list test_list = [(3, 4, 5), (4, 5, 7), (1, 4)] # printing original list print("The original list : " + str(test_list)) # Unique elements in nested tuple x = [] for i in test_list: i = list(i) x.extend(i) res = list(set(x)) # printing result print("Unique elements in nested tuples are : " + str(res))
#Output : The original list : [(3, 4, 5), (4, 5, 7), (1, 4)]
Python Program to get unique elements in nested tuple # Python3 code to demonstrate working of # Unique elements in nested tuple # initialize list test_list = [(3, 4, 5), (4, 5, 7), (1, 4)] # printing original list print("The original list : " + str(test_list)) # Unique elements in nested tuple x = [] for i in test_list: i = list(i) x.extend(i) res = list(set(x)) # printing result print("Unique elements in nested tuples are : " + str(res)) #Output : The original list : [(3, 4, 5), (4, 5, 7), (1, 4)] [END]
Python Program to get unique elements in nested tuple
https://www.geeksforgeeks.org/python-how-to-get-unique-elements-in-nested-tuple/
# Python3 code to demonstrate working of # Unique elements in nested tuple from collections import Counter # initialize list test_list = [(3, 4, 5), (4, 5, 7), (1, 4)] # printing original list print("The original list : " + str(test_list)) # Unique elements in nested tuple x = [] for i in test_list: x.extend(list(i)) freq = Counter(x) res = list(freq.keys()) res.sort() # printing result print("Unique elements in nested tuples are : " + str(res))
#Output : The original list : [(3, 4, 5), (4, 5, 7), (1, 4)]
Python Program to get unique elements in nested tuple # Python3 code to demonstrate working of # Unique elements in nested tuple from collections import Counter # initialize list test_list = [(3, 4, 5), (4, 5, 7), (1, 4)] # printing original list print("The original list : " + str(test_list)) # Unique elements in nested tuple x = [] for i in test_list: x.extend(list(i)) freq = Counter(x) res = list(freq.keys()) res.sort() # printing result print("Unique elements in nested tuples are : " + str(res)) #Output : The original list : [(3, 4, 5), (4, 5, 7), (1, 4)] [END]
Python Program to get unique elements in nested tuple
https://www.geeksforgeeks.org/python-how-to-get-unique-elements-in-nested-tuple/
# Python3 code to demonstrate working of # Unique elements in nested tuple import operator as op # initialize list test_list = [(3, 4, 5), (4, 5, 7), (1, 4)] # printing original list print("The original list : " + str(test_list)) # Unique elements in nested tuple # Using nested loop + set() res = [] temp = set() for inner in test_list: for ele in inner: if op.countOf(temp, ele) == 0: temp.add(ele) res.append(ele) res.sort() # printing result print("Unique elements in nested tuples are : " + str(res))
#Output : The original list : [(3, 4, 5), (4, 5, 7), (1, 4)]
Python Program to get unique elements in nested tuple # Python3 code to demonstrate working of # Unique elements in nested tuple import operator as op # initialize list test_list = [(3, 4, 5), (4, 5, 7), (1, 4)] # printing original list print("The original list : " + str(test_list)) # Unique elements in nested tuple # Using nested loop + set() res = [] temp = set() for inner in test_list: for ele in inner: if op.countOf(temp, ele) == 0: temp.add(ele) res.append(ele) res.sort() # printing result print("Unique elements in nested tuples are : " + str(res)) #Output : The original list : [(3, 4, 5), (4, 5, 7), (1, 4)] [END]
Python Program to get unique elements in nested tuple
https://www.geeksforgeeks.org/python-how-to-get-unique-elements-in-nested-tuple/
# Python3 code to demonstrate working of # Unique elements in nested tuple # initialize list test_list = [(3, 4, 5), (4, 5, 7), (1, 4)] # printing original list print("The original list : " + str(test_list)) # Unique elements in nested tuple # Using list comprehension and set conversion res = sorted(set([x for inner in test_list for x in inner])) # printing result print("Unique elements in nested tuples are : " + str(res))
#Output : The original list : [(3, 4, 5), (4, 5, 7), (1, 4)]
Python Program to get unique elements in nested tuple # Python3 code to demonstrate working of # Unique elements in nested tuple # initialize list test_list = [(3, 4, 5), (4, 5, 7), (1, 4)] # printing original list print("The original list : " + str(test_list)) # Unique elements in nested tuple # Using list comprehension and set conversion res = sorted(set([x for inner in test_list for x in inner])) # printing result print("Unique elements in nested tuples are : " + str(res)) #Output : The original list : [(3, 4, 5), (4, 5, 7), (1, 4)] [END]
Python program to Concatenate tuples to nested tuples
https://www.geeksforgeeks.org/python-how-to-concatenate-tuples-to-nested-tuples/
# Python3 code to demonstrate working of # Concatenating tuples to nested tuples # using + operator + ", " operator during initialization # initialize tuples test_tup1 = ((3, 4),) test_tup2 = ((5, 6),) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Concatenating tuples to nested tuples # using + operator + ", " operator during initialization res = test_tup1 + test_tup2 # printing result print("Tuples after Concatenating : " + str(res))
#Output : The original tuple 1 : ((3, 4), )
Python program to Concatenate tuples to nested tuples # Python3 code to demonstrate working of # Concatenating tuples to nested tuples # using + operator + ", " operator during initialization # initialize tuples test_tup1 = ((3, 4),) test_tup2 = ((5, 6),) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Concatenating tuples to nested tuples # using + operator + ", " operator during initialization res = test_tup1 + test_tup2 # printing result print("Tuples after Concatenating : " + str(res)) #Output : The original tuple 1 : ((3, 4), ) [END]
Python program to Concatenate tuples to nested tuples
https://www.geeksforgeeks.org/python-how-to-concatenate-tuples-to-nested-tuples/
# Python3 code to demonstrate working of # Concatenating tuples to nested tuples # Using ", " operator during concatenation # initialize tuples test_tup1 = (3, 4) test_tup2 = (5, 6) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Concatenating tuples to nested tuples # Using ", " operator during concatenation res = (test_tup1,) + (test_tup2,) # printing result print("Tuples after Concatenating : " + str(res))
#Output : The original tuple 1 : ((3, 4), )
Python program to Concatenate tuples to nested tuples # Python3 code to demonstrate working of # Concatenating tuples to nested tuples # Using ", " operator during concatenation # initialize tuples test_tup1 = (3, 4) test_tup2 = (5, 6) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Concatenating tuples to nested tuples # Using ", " operator during concatenation res = (test_tup1,) + (test_tup2,) # printing result print("Tuples after Concatenating : " + str(res)) #Output : The original tuple 1 : ((3, 4), ) [END]
Python program to Concatenate tuples to nested tuples
https://www.geeksforgeeks.org/python-how-to-concatenate-tuples-to-nested-tuples/
# Python3 code to demonstrate working of # Concatenating tuples to nested tuples # using + operator + ", " operator during initialization # initialize tuples test_tup1 = ((3, 4),) test_tup2 = ((5, 6),) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Concatenating tuples to nested tuples test_tup1 = list(test_tup1) test_tup2 = list(test_tup2) test_tup1.extend(test_tup2) # printing result print("Tuples after Concatenating : " + str(tuple(test_tup1)))
#Output : The original tuple 1 : ((3, 4), )
Python program to Concatenate tuples to nested tuples # Python3 code to demonstrate working of # Concatenating tuples to nested tuples # using + operator + ", " operator during initialization # initialize tuples test_tup1 = ((3, 4),) test_tup2 = ((5, 6),) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Concatenating tuples to nested tuples test_tup1 = list(test_tup1) test_tup2 = list(test_tup2) test_tup1.extend(test_tup2) # printing result print("Tuples after Concatenating : " + str(tuple(test_tup1))) #Output : The original tuple 1 : ((3, 4), ) [END]
Python program to Concatenate tuples to nested tuples
https://www.geeksforgeeks.org/python-how-to-concatenate-tuples-to-nested-tuples/
import itertools test_tup1 = ((3, 4),) test_tup2 = ((5, 6),) # using itertools.chain() to concatenate tuples to nested tuples res = tuple(itertools.chain(test_tup1, test_tup2)) # printing result print("Tuples after Concatenating : ", res)
#Output : The original tuple 1 : ((3, 4), )
Python program to Concatenate tuples to nested tuples import itertools test_tup1 = ((3, 4),) test_tup2 = ((5, 6),) # using itertools.chain() to concatenate tuples to nested tuples res = tuple(itertools.chain(test_tup1, test_tup2)) # printing result print("Tuples after Concatenating : ", res) #Output : The original tuple 1 : ((3, 4), ) [END]
Python program to Concatenate tuples to nested tuples
https://www.geeksforgeeks.org/python-how-to-concatenate-tuples-to-nested-tuples/
# Python3 code to demonstrate working of # Concatenating tuples to nested tuples # using functools.reduce() method # import functools module import functools # initialize tuples test_tup1 = ((3, 4),) test_tup2 = ((5, 6),) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Concatenating tuples to nested tuples # using functools.reduce() method res = functools.reduce(lambda x, y: x + y, (test_tup1, test_tup2)) # printing result print("Tuples after Concatenating : " + str(res))
#Output : The original tuple 1 : ((3, 4), )
Python program to Concatenate tuples to nested tuples # Python3 code to demonstrate working of # Concatenating tuples to nested tuples # using functools.reduce() method # import functools module import functools # initialize tuples test_tup1 = ((3, 4),) test_tup2 = ((5, 6),) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Concatenating tuples to nested tuples # using functools.reduce() method res = functools.reduce(lambda x, y: x + y, (test_tup1, test_tup2)) # printing result print("Tuples after Concatenating : " + str(res)) #Output : The original tuple 1 : ((3, 4), ) [END]
Python program to Concatenate tuples to nested tuples
https://www.geeksforgeeks.org/python-how-to-concatenate-tuples-to-nested-tuples/
# Python3 code to demonstrate working of # Concatenating tuples to nested tuples # using extend() method of list class # initialize tuples test_tup1 = (3, 4) test_tup2 = (5, 6) # create an empty list lst = [] # Concatenating tuples to nested tuples # using extend() method of list class lst.extend(test_tup1) lst.extend(test_tup2) res = tuple([lst[i : i + 2] for i in range(0, len(lst), 2)]) # printing result print("Tuples after Concatenating : ", res)
#Output : The original tuple 1 : ((3, 4), )
Python program to Concatenate tuples to nested tuples # Python3 code to demonstrate working of # Concatenating tuples to nested tuples # using extend() method of list class # initialize tuples test_tup1 = (3, 4) test_tup2 = (5, 6) # create an empty list lst = [] # Concatenating tuples to nested tuples # using extend() method of list class lst.extend(test_tup1) lst.extend(test_tup2) res = tuple([lst[i : i + 2] for i in range(0, len(lst), 2)]) # printing result print("Tuples after Concatenating : ", res) #Output : The original tuple 1 : ((3, 4), ) [END]
Python - Sort by Frequency of second element in Tuple list
https://www.geeksforgeeks.org/python-sort-by-frequency-of-second-element-in-tuple-list/
# Python3 code to demonstrate working of # Sort by Frequency of second element in Tuple List # Using sorted() + loop + defaultdict() + lambda from collections import defaultdict # initializing list test_list = [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)] # printing original list print("The original list is : " + str(test_list)) # constructing mapping freq_map = defaultdict(int) for idx, val in test_list: freq_map[val] += 1 # performing sort of result res = sorted(test_list, key=lambda ele: freq_map[ele[1]], reverse=True) # printing results print("Sorted List of tuples : " + str(res))
#Output : The original list is : [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)]
Python - Sort by Frequency of second element in Tuple list # Python3 code to demonstrate working of # Sort by Frequency of second element in Tuple List # Using sorted() + loop + defaultdict() + lambda from collections import defaultdict # initializing list test_list = [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)] # printing original list print("The original list is : " + str(test_list)) # constructing mapping freq_map = defaultdict(int) for idx, val in test_list: freq_map[val] += 1 # performing sort of result res = sorted(test_list, key=lambda ele: freq_map[ele[1]], reverse=True) # printing results print("Sorted List of tuples : " + str(res)) #Output : The original list is : [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)] [END]
Python - Sort by Frequency of second element in Tuple list
https://www.geeksforgeeks.org/python-sort-by-frequency-of-second-element-in-tuple-list/
# Python3 code to demonstrate working of # Sort by Frequency of second element in Tuple List # Using Counter() + lambda + sorted() from collections import Counter # initializing list test_list = [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)] # printing original list print("The original list is : " + str(test_list)) # constructing mapping using Counter freq_map = Counter(val for key, val in test_list) # performing sort of result res = sorted(test_list, key=lambda ele: freq_map[ele[1]], reverse=True) # printing results print("Sorted List of tuples : " + str(res))
#Output : The original list is : [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)]
Python - Sort by Frequency of second element in Tuple list # Python3 code to demonstrate working of # Sort by Frequency of second element in Tuple List # Using Counter() + lambda + sorted() from collections import Counter # initializing list test_list = [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)] # printing original list print("The original list is : " + str(test_list)) # constructing mapping using Counter freq_map = Counter(val for key, val in test_list) # performing sort of result res = sorted(test_list, key=lambda ele: freq_map[ele[1]], reverse=True) # printing results print("Sorted List of tuples : " + str(res)) #Output : The original list is : [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)] [END]
Python - Sort by Frequency of second element in Tuple list
https://www.geeksforgeeks.org/python-sort-by-frequency-of-second-element-in-tuple-list/
from itertools import groupby # import groupby function from itertools module def sort_by_frequency( test_list, ): # define function called sort_by_frequency that takes a list called test_list as input freq_dict = { val: len(list(group)) for val, group in groupby(sorted(test_list, key=lambda x: x[1]), lambda x: x[1]) } # create a dictionary called freq_dict where each key is a unique second element of a tuple in test_list and its value is the number of times that second element appears in test_list # we do this by using the groupby function to group the tuples in test_list by their second element, then using len to count the number of tuples in each group # we use sorted to sort the list of tuples by their second element before using groupby, and we use a lambda function to specify that we want to group by the second element of each tuple # the resulting dictionary has keys that are unique second elements from test_list and values that are the frequency of each second element in test_list return sorted(test_list, key=lambda x: freq_dict[x[1]], reverse=True) # sort the original list of tuples (test_list) based on the values in freq_dict # we use a lambda function to specify that we want to sort by the value in freq_dict corresponding to the second element of each tuple in test_list # we sort the list in reverse order (highest frequency first) test_list = [(6, 5), (1, 7), (2, 5), (8, 7), (9, 8), (3, 7)] # define test_list print("The original list is : " + str(test_list)) # print the original list print( "The sorted list is : " + str(sort_by_frequency(test_list)) ) # print the sorted list returned by the sort_by_frequency function
#Output : The original list is : [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)]
Python - Sort by Frequency of second element in Tuple list from itertools import groupby # import groupby function from itertools module def sort_by_frequency( test_list, ): # define function called sort_by_frequency that takes a list called test_list as input freq_dict = { val: len(list(group)) for val, group in groupby(sorted(test_list, key=lambda x: x[1]), lambda x: x[1]) } # create a dictionary called freq_dict where each key is a unique second element of a tuple in test_list and its value is the number of times that second element appears in test_list # we do this by using the groupby function to group the tuples in test_list by their second element, then using len to count the number of tuples in each group # we use sorted to sort the list of tuples by their second element before using groupby, and we use a lambda function to specify that we want to group by the second element of each tuple # the resulting dictionary has keys that are unique second elements from test_list and values that are the frequency of each second element in test_list return sorted(test_list, key=lambda x: freq_dict[x[1]], reverse=True) # sort the original list of tuples (test_list) based on the values in freq_dict # we use a lambda function to specify that we want to sort by the value in freq_dict corresponding to the second element of each tuple in test_list # we sort the list in reverse order (highest frequency first) test_list = [(6, 5), (1, 7), (2, 5), (8, 7), (9, 8), (3, 7)] # define test_list print("The original list is : " + str(test_list)) # print the original list print( "The sorted list is : " + str(sort_by_frequency(test_list)) ) # print the sorted list returned by the sort_by_frequency function #Output : The original list is : [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)] [END]
Python - Sort by Frequency of second element in Tuple list
https://www.geeksforgeeks.org/python-sort-by-frequency-of-second-element-in-tuple-list/
import numpy as np # initializing list test_list = [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)] # printing original list print("The original list is : " + str(test_list)) # convert the list to a numpy array arr = np.array(test_list) # get the frequency of each second element using numpy's unique function counts = np.unique(arr[:, 1], return_counts=True) # sort the indices based on the frequency of the second element using numpy's argsort function sorted_indices = np.argsort(-counts[1]) # create an empty array to store the sorted tuples sorted_arr = np.empty_like(arr) # iterate over the sorted indices and fill in the sorted array start = 0 for i in sorted_indices: freq = counts[1][i] indices = np.where(arr[:, 1] == counts[0][i])[0] end = start + freq sorted_arr[start:end] = arr[indices] start = end # convert the sorted array back to a list of tuples res = [tuple(row) for row in sorted_arr] # printing results print("Sorted List of tuples : " + str(res))
#Output : The original list is : [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)]
Python - Sort by Frequency of second element in Tuple list import numpy as np # initializing list test_list = [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)] # printing original list print("The original list is : " + str(test_list)) # convert the list to a numpy array arr = np.array(test_list) # get the frequency of each second element using numpy's unique function counts = np.unique(arr[:, 1], return_counts=True) # sort the indices based on the frequency of the second element using numpy's argsort function sorted_indices = np.argsort(-counts[1]) # create an empty array to store the sorted tuples sorted_arr = np.empty_like(arr) # iterate over the sorted indices and fill in the sorted array start = 0 for i in sorted_indices: freq = counts[1][i] indices = np.where(arr[:, 1] == counts[0][i])[0] end = start + freq sorted_arr[start:end] = arr[indices] start = end # convert the sorted array back to a list of tuples res = [tuple(row) for row in sorted_arr] # printing results print("Sorted List of tuples : " + str(res)) #Output : The original list is : [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)] [END]
Python - Sort lists in tuple
https://www.geeksforgeeks.org/python-sort-lists-in-tuple/
# Python3 code to demonstrate working of # Sort lists in tuple # Using tuple() + sorted() + generator expression # Initializing tuple test_tup = ([7, 5, 4], [8, 2, 4], [0, 7, 5]) # printing original tuple print("The original tuple is : " + str(test_tup)) # Sort lists in tuple # Using tuple() + sorted() + generator expression res = tuple((sorted(sub) for sub in test_tup)) # printing result print("The tuple after sorting lists : " + str(res))
#Output : The original tuple is : ([7, 5, 4], [8, 2, 4], [0, 7, 5])
Python - Sort lists in tuple # Python3 code to demonstrate working of # Sort lists in tuple # Using tuple() + sorted() + generator expression # Initializing tuple test_tup = ([7, 5, 4], [8, 2, 4], [0, 7, 5]) # printing original tuple print("The original tuple is : " + str(test_tup)) # Sort lists in tuple # Using tuple() + sorted() + generator expression res = tuple((sorted(sub) for sub in test_tup)) # printing result print("The tuple after sorting lists : " + str(res)) #Output : The original tuple is : ([7, 5, 4], [8, 2, 4], [0, 7, 5]) [END]
Python - Sort lists in tuple
https://www.geeksforgeeks.org/python-sort-lists-in-tuple/
# Python3 code to demonstrate working of # Sort lists in tuple # Using map() + sorted() # Initializing tuple test_tup = ([7, 5, 4], [8, 2, 4], [0, 7, 5]) # printing original tuple print("The original tuple is : " + str(test_tup)) # Sort lists in tuple # Using map() + sorted() res = tuple(map(sorted, test_tup)) # printing result print("The tuple after sorting lists : " + str(res))
#Output : The original tuple is : ([7, 5, 4], [8, 2, 4], [0, 7, 5])
Python - Sort lists in tuple # Python3 code to demonstrate working of # Sort lists in tuple # Using map() + sorted() # Initializing tuple test_tup = ([7, 5, 4], [8, 2, 4], [0, 7, 5]) # printing original tuple print("The original tuple is : " + str(test_tup)) # Sort lists in tuple # Using map() + sorted() res = tuple(map(sorted, test_tup)) # printing result print("The tuple after sorting lists : " + str(res)) #Output : The original tuple is : ([7, 5, 4], [8, 2, 4], [0, 7, 5]) [END]
Python - Sort lists in tuple
https://www.geeksforgeeks.org/python-sort-lists-in-tuple/
original_tuple = ([7, 5, 4], [8, 2, 4], [0, 7, 5]) sorted_lists = () for lst in original_tuple: sorted_list = sorted(lst) sorted_lists += (sorted_list,) print(sorted_lists)
#Output : The original tuple is : ([7, 5, 4], [8, 2, 4], [0, 7, 5])
Python - Sort lists in tuple original_tuple = ([7, 5, 4], [8, 2, 4], [0, 7, 5]) sorted_lists = () for lst in original_tuple: sorted_list = sorted(lst) sorted_lists += (sorted_list,) print(sorted_lists) #Output : The original tuple is : ([7, 5, 4], [8, 2, 4], [0, 7, 5]) [END]
Python program to Order Tuples using external List
https://www.geeksforgeeks.org/python-order-tuples-by-list/
# Python3 code to demonstrate working of # Order Tuples by List # Using dict() + list comprehension # initializing list test_list = [("Gfg", 3), ("best", 9), ("CS", 10), ("Geeks", 2)] # printing original list print("The original list is : " + str(test_list)) # initializing order list ord_list = ["Geeks", "best", "CS", "Gfg"] # Order Tuples by List # Using dict() + list comprehension temp = dict(test_list) res = [(key, temp[key]) for key in ord_list] # printing result print("The ordered tuple list : " + str(res))
#Output : The original list is : [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)]
Python program to Order Tuples using external List # Python3 code to demonstrate working of # Order Tuples by List # Using dict() + list comprehension # initializing list test_list = [("Gfg", 3), ("best", 9), ("CS", 10), ("Geeks", 2)] # printing original list print("The original list is : " + str(test_list)) # initializing order list ord_list = ["Geeks", "best", "CS", "Gfg"] # Order Tuples by List # Using dict() + list comprehension temp = dict(test_list) res = [(key, temp[key]) for key in ord_list] # printing result print("The ordered tuple list : " + str(res)) #Output : The original list is : [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)] [END]
Python program to Order Tuples using external List
https://www.geeksforgeeks.org/python-order-tuples-by-list/
# Python3 code to demonstrate working of # Order Tuples by List # Using setdefault() + sorted() + lambda # initializing list test_list = [("Gfg", 3), ("best", 9), ("CS", 10), ("Geeks", 2)] # printing original list print("The original list is : " + str(test_list)) # initializing order list ord_list = ["Geeks", "best", "CS", "Gfg"] # Order Tuples by List # Using setdefault() + sorted() + lambda temp = dict() for key, ele in enumerate(ord_list): temp.setdefault(ele, []).append(key) res = sorted(test_list, key=lambda ele: temp[ele[0]].pop()) # printing result print("The ordered tuple list : " + str(res))
#Output : The original list is : [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)]
Python program to Order Tuples using external List # Python3 code to demonstrate working of # Order Tuples by List # Using setdefault() + sorted() + lambda # initializing list test_list = [("Gfg", 3), ("best", 9), ("CS", 10), ("Geeks", 2)] # printing original list print("The original list is : " + str(test_list)) # initializing order list ord_list = ["Geeks", "best", "CS", "Gfg"] # Order Tuples by List # Using setdefault() + sorted() + lambda temp = dict() for key, ele in enumerate(ord_list): temp.setdefault(ele, []).append(key) res = sorted(test_list, key=lambda ele: temp[ele[0]].pop()) # printing result print("The ordered tuple list : " + str(res)) #Output : The original list is : [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)] [END]
Python program to Order Tuples using external List
https://www.geeksforgeeks.org/python-order-tuples-by-list/
# Python3 code to demonstrate working of # Order Tuples by List # initializing list test_list = [("Gfg", 3), ("best", 9), ("CS", 10), ("Geeks", 2)] # printing original list print("The original list is : " + str(test_list)) # initializing order list ord_list = ["Geeks", "best", "CS", "Gfg"] res = [] x = [] for i in test_list: x.append(i[0]) for i in ord_list: if i in x: res.append(test_list[x.index(i)]) # printing result print("The ordered tuple list : " + str(res))
#Output : The original list is : [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)]
Python program to Order Tuples using external List # Python3 code to demonstrate working of # Order Tuples by List # initializing list test_list = [("Gfg", 3), ("best", 9), ("CS", 10), ("Geeks", 2)] # printing original list print("The original list is : " + str(test_list)) # initializing order list ord_list = ["Geeks", "best", "CS", "Gfg"] res = [] x = [] for i in test_list: x.append(i[0]) for i in ord_list: if i in x: res.append(test_list[x.index(i)]) # printing result print("The ordered tuple list : " + str(res)) #Output : The original list is : [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)] [END]
Python program to Order Tuples using external List
https://www.geeksforgeeks.org/python-order-tuples-by-list/
def order_tuples_by_list(test_list, ord_list): return sorted(test_list, key=lambda x: ord_list.index(x[0])) test_list = [("Gfg", 10), ("best", 3), ("CS", 8), ("Geeks", 7)] ord_list = ["Geeks", "best", "CS", "Gfg"] print(order_tuples_by_list(test_list, ord_list))
#Output : The original list is : [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)]
Python program to Order Tuples using external List def order_tuples_by_list(test_list, ord_list): return sorted(test_list, key=lambda x: ord_list.index(x[0])) test_list = [("Gfg", 10), ("best", 3), ("CS", 8), ("Geeks", 7)] ord_list = ["Geeks", "best", "CS", "Gfg"] print(order_tuples_by_list(test_list, ord_list)) #Output : The original list is : [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)] [END]
Python program to Order Tuples using external List
https://www.geeksforgeeks.org/python-order-tuples-by-list/
from operator import itemgetter # input original_list = [("Gfg", 3), ("best", 9), ("CS", 10), ("Geeks", 2)] # sort the list using the sorted() function with itemgetter() function as its key parameter ordered_list = sorted(original_list, key=itemgetter(1)) # output print(ordered_list)
#Output : The original list is : [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)]
Python program to Order Tuples using external List from operator import itemgetter # input original_list = [("Gfg", 3), ("best", 9), ("CS", 10), ("Geeks", 2)] # sort the list using the sorted() function with itemgetter() function as its key parameter ordered_list = sorted(original_list, key=itemgetter(1)) # output print(ordered_list) #Output : The original list is : [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)] [END]
Python program to Order Tuples using external List
https://www.geeksforgeeks.org/python-order-tuples-by-list/
from functools import reduce # initializing list test_list = [("Gfg", 3), ("best", 9), ("CS", 10), ("Geeks", 2)] # printing original list print("The original list is : " + str(test_list)) # initializing order list ord_list = ["Geeks", "best", "CS", "Gfg"] # using reduce() to sort the list based on order list res = reduce( lambda acc, key: acc + [ele for ele in test_list if ele[0] == key], ord_list, [] ) # printing result print("The ordered tuple list : " + str(res)) # This is code is contributed by Vinay Pinjala.
#Output : The original list is : [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)]
Python program to Order Tuples using external List from functools import reduce # initializing list test_list = [("Gfg", 3), ("best", 9), ("CS", 10), ("Geeks", 2)] # printing original list print("The original list is : " + str(test_list)) # initializing order list ord_list = ["Geeks", "best", "CS", "Gfg"] # using reduce() to sort the list based on order list res = reduce( lambda acc, key: acc + [ele for ele in test_list if ele[0] == key], ord_list, [] ) # printing result print("The ordered tuple list : " + str(res)) # This is code is contributed by Vinay Pinjala. #Output : The original list is : [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)] [END]
Python - Filter Tuples by Kth element from list
https://www.geeksforgeeks.org/python-filter-tuples-by-kth-element-from-list/
# Python3 code to demonstrate working of # Filter Tuples by Kth element from List # Using list comprehension # initializing list test_list = [("GFg", 5, 9), ("is", 4, 3), ("best", 10, 29)] # printing original list print("The original list is : " + str(test_list)) # initializing check_list check_list = [4, 2, 8, 10] # initializing K K = 1 # checking for presence on Kth element in list # one liner res = [sub for sub in test_list if sub[K] in check_list] # printing result print("The filtered tuples : " + str(res))
#Output : The original list is : [('GFg', 5, 9), ('is', 4, 3), ('best', 10, 29)]
Python - Filter Tuples by Kth element from list # Python3 code to demonstrate working of # Filter Tuples by Kth element from List # Using list comprehension # initializing list test_list = [("GFg", 5, 9), ("is", 4, 3), ("best", 10, 29)] # printing original list print("The original list is : " + str(test_list)) # initializing check_list check_list = [4, 2, 8, 10] # initializing K K = 1 # checking for presence on Kth element in list # one liner res = [sub for sub in test_list if sub[K] in check_list] # printing result print("The filtered tuples : " + str(res)) #Output : The original list is : [('GFg', 5, 9), ('is', 4, 3), ('best', 10, 29)] [END]
Python - Filter Tuples by Kth element from list
https://www.geeksforgeeks.org/python-filter-tuples-by-kth-element-from-list/
# Python3 code to demonstrate working of # Filter Tuples by Kth element from List # Using filter() + lambda # initializing list test_list = [("GFg", 5, 9), ("is", 4, 3), ("best", 10, 29)] # printing original list print("The original list is : " + str(test_list)) # initializing check_list check_list = [4, 2, 8, 10] # initializing K K = 1 # filter() perform filter, lambda func. checks for presence # one liner res = list(filter(lambda sub: sub[K] in check_list, test_list)) # printing result print("The filtered tuples : " + str(res))
#Output : The original list is : [('GFg', 5, 9), ('is', 4, 3), ('best', 10, 29)]
Python - Filter Tuples by Kth element from list # Python3 code to demonstrate working of # Filter Tuples by Kth element from List # Using filter() + lambda # initializing list test_list = [("GFg", 5, 9), ("is", 4, 3), ("best", 10, 29)] # printing original list print("The original list is : " + str(test_list)) # initializing check_list check_list = [4, 2, 8, 10] # initializing K K = 1 # filter() perform filter, lambda func. checks for presence # one liner res = list(filter(lambda sub: sub[K] in check_list, test_list)) # printing result print("The filtered tuples : " + str(res)) #Output : The original list is : [('GFg', 5, 9), ('is', 4, 3), ('best', 10, 29)] [END]
Python - Filter Tuples by Kth element from list
https://www.geeksforgeeks.org/python-filter-tuples-by-kth-element-from-list/
# Python3 code to demonstrate working of # Filter Tuples by Kth element from List # Using for loop # initializing list test_list = [("GFg", 5, 9), ("is", 4, 3), ("best", 10, 29)] # printing original list print("The original list is : " + str(test_list)) # initializing check_list check_list = [4, 2, 8, 10] # initializing K K = 1 # initializing empty result list res = [] # iterating over tuples in test_list for tup in test_list: # checking if Kth element is in check_list if tup[K] in check_list: # appending tuple to result list res.append(tup) # printing result print("The filtered tuples : " + str(res))
#Output : The original list is : [('GFg', 5, 9), ('is', 4, 3), ('best', 10, 29)]
Python - Filter Tuples by Kth element from list # Python3 code to demonstrate working of # Filter Tuples by Kth element from List # Using for loop # initializing list test_list = [("GFg", 5, 9), ("is", 4, 3), ("best", 10, 29)] # printing original list print("The original list is : " + str(test_list)) # initializing check_list check_list = [4, 2, 8, 10] # initializing K K = 1 # initializing empty result list res = [] # iterating over tuples in test_list for tup in test_list: # checking if Kth element is in check_list if tup[K] in check_list: # appending tuple to result list res.append(tup) # printing result print("The filtered tuples : " + str(res)) #Output : The original list is : [('GFg', 5, 9), ('is', 4, 3), ('best', 10, 29)] [END]
Python - Filter Tuples by Kth element from list
https://www.geeksforgeeks.org/python-filter-tuples-by-kth-element-from-list/
# Python program for the above approach # Function to filter tuples def filter_tuples(test_list, K, check_list): if not test_list: return [] if test_list[0][K] in check_list: return [test_list[0]] + filter_tuples(test_list[1:], K, check_list) else: return filter_tuples(test_list[1:], K, check_list) # initializing list test_list = [("GFg", 5, 9), ("is", 4, 3), ("best", 10, 29)] # initializing check_list check_list = [4, 2, 8, 10] # initializing K K = 1 # calling function and storing result in res res = filter_tuples(test_list, K, check_list) # printing original list print("The original list is : " + str(test_list)) # printing result print("The filtered tuples : " + str(res))
#Output : The original list is : [('GFg', 5, 9), ('is', 4, 3), ('best', 10, 29)]
Python - Filter Tuples by Kth element from list # Python program for the above approach # Function to filter tuples def filter_tuples(test_list, K, check_list): if not test_list: return [] if test_list[0][K] in check_list: return [test_list[0]] + filter_tuples(test_list[1:], K, check_list) else: return filter_tuples(test_list[1:], K, check_list) # initializing list test_list = [("GFg", 5, 9), ("is", 4, 3), ("best", 10, 29)] # initializing check_list check_list = [4, 2, 8, 10] # initializing K K = 1 # calling function and storing result in res res = filter_tuples(test_list, K, check_list) # printing original list print("The original list is : " + str(test_list)) # printing result print("The filtered tuples : " + str(res)) #Output : The original list is : [('GFg', 5, 9), ('is', 4, 3), ('best', 10, 29)] [END]
Python - Closest Pair to Kth index element in tuple
https://www.geeksforgeeks.org/python-closest-pair-to-kth-index-element-in-tuple/
# Python3 code to demonstrate working of # Closest Pair to Kth index element in Tuple # Using enumerate() + loop # initializing list test_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)] # printing original list print("The original list is : " + str(test_list)) # initializing tuple tup = (17, 23) # initializing K K = 1 # Closest Pair to Kth index element in Tuple # Using enumerate() + loop min_dif, res = 999999999, None for idx, val in enumerate(test_list): dif = abs(tup[K - 1] - val[K - 1]) if dif < min_dif: min_dif, res = dif, idx # printing result print("The nearest tuple to Kth index element is : " + str(test_list[res]))
#Output : The original list is : [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]
Python - Closest Pair to Kth index element in tuple # Python3 code to demonstrate working of # Closest Pair to Kth index element in Tuple # Using enumerate() + loop # initializing list test_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)] # printing original list print("The original list is : " + str(test_list)) # initializing tuple tup = (17, 23) # initializing K K = 1 # Closest Pair to Kth index element in Tuple # Using enumerate() + loop min_dif, res = 999999999, None for idx, val in enumerate(test_list): dif = abs(tup[K - 1] - val[K - 1]) if dif < min_dif: min_dif, res = dif, idx # printing result print("The nearest tuple to Kth index element is : " + str(test_list[res])) #Output : The original list is : [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)] [END]
Python - Closest Pair to Kth index element in tuple
https://www.geeksforgeeks.org/python-closest-pair-to-kth-index-element-in-tuple/
# Python3 code to demonstrate working of # Closest Pair to Kth index element in Tuple # Using min() + lambda # initializing list test_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)] # printing original list print("The original list is : " + str(test_list)) # initializing tuple tup = (17, 23) # initializing K K = 1 # Closest Pair to Kth index element in Tuple # Using min() + lambda res = min( range(len(test_list)), key=lambda sub: abs(test_list[sub][K - 1] - tup[K - 1]) ) # printing result print("The nearest tuple to Kth index element is : " + str(test_list[res]))
#Output : The original list is : [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]
Python - Closest Pair to Kth index element in tuple # Python3 code to demonstrate working of # Closest Pair to Kth index element in Tuple # Using min() + lambda # initializing list test_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)] # printing original list print("The original list is : " + str(test_list)) # initializing tuple tup = (17, 23) # initializing K K = 1 # Closest Pair to Kth index element in Tuple # Using min() + lambda res = min( range(len(test_list)), key=lambda sub: abs(test_list[sub][K - 1] - tup[K - 1]) ) # printing result print("The nearest tuple to Kth index element is : " + str(test_list[res])) #Output : The original list is : [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)] [END]
Python - Closest Pair to Kth index element in tuple
https://www.geeksforgeeks.org/python-closest-pair-to-kth-index-element-in-tuple/
# initializing list test_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)] # initializing tuple tup = (17, 23) # initializing K K = 1 # Using a lambda function and the min() function res = min(test_list, key=lambda x: abs(x[K - 1] - tup[K - 1])) # printing result print("The nearest tuple to Kth index element is : " + str(res))
#Output : The original list is : [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]
Python - Closest Pair to Kth index element in tuple # initializing list test_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)] # initializing tuple tup = (17, 23) # initializing K K = 1 # Using a lambda function and the min() function res = min(test_list, key=lambda x: abs(x[K - 1] - tup[K - 1])) # printing result print("The nearest tuple to Kth index element is : " + str(res)) #Output : The original list is : [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)] [END]
Python - Closest Pair to Kth index element in tuple
https://www.geeksforgeeks.org/python-closest-pair-to-kth-index-element-in-tuple/
import heapq # initializing the list of tuples test_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)] # initializing the target tuple tup = (17, 23) # initializing the index of the element to compare in each tuple K = 1 # using the heapq.nsmallest() function to get the tuple with the smallest difference between the Kth element and the corresponding element in the target tuple res = heapq.nsmallest(1, test_list, key=lambda x: abs(x[K - 1] - tup[K - 1]))[0] # printing the result print("The nearest tuple to Kth index element is : " + str(res)) # This code is contributed by Jyothi pinjala.
#Output : The original list is : [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]
Python - Closest Pair to Kth index element in tuple import heapq # initializing the list of tuples test_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)] # initializing the target tuple tup = (17, 23) # initializing the index of the element to compare in each tuple K = 1 # using the heapq.nsmallest() function to get the tuple with the smallest difference between the Kth element and the corresponding element in the target tuple res = heapq.nsmallest(1, test_list, key=lambda x: abs(x[K - 1] - tup[K - 1]))[0] # printing the result print("The nearest tuple to Kth index element is : " + str(res)) # This code is contributed by Jyothi pinjala. #Output : The original list is : [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)] [END]
Python - Closest Pair to Kth index element in tuple
https://www.geeksforgeeks.org/python-closest-pair-to-kth-index-element-in-tuple/
# initializing the list of tuples test_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)] # initializing the target tuple tup = (17, 23) # initializing the index of the element to compare in each tuple K = 1 # define a custom key function def key_func(t): return abs(t[K - 1] - tup[K - 1]) # use the sorted() function to sort the list of tuples based on the custom key function sorted_list = sorted(test_list, key=key_func) # retrieve the first tuple from the sorted list res = sorted_list[0] # print the result print("The nearest tuple to Kth index element is : " + str(res))
#Output : The original list is : [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]
Python - Closest Pair to Kth index element in tuple # initializing the list of tuples test_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)] # initializing the target tuple tup = (17, 23) # initializing the index of the element to compare in each tuple K = 1 # define a custom key function def key_func(t): return abs(t[K - 1] - tup[K - 1]) # use the sorted() function to sort the list of tuples based on the custom key function sorted_list = sorted(test_list, key=key_func) # retrieve the first tuple from the sorted list res = sorted_list[0] # print the result print("The nearest tuple to Kth index element is : " + str(res)) #Output : The original list is : [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)] [END]
Python - Tuple List intersection (Order Irrespective)
https://www.geeksforgeeks.org/python-tuple-list-intersection-order-irrespective/
# Python3 code to demonstrate working of # Tuple List intersection [ Order irrespective ] # Using sorted() + set() + & operator + list comprehension # initializing lists test_list1 = [(3, 4), (5, 6), (9, 10), (4, 5)] test_list2 = [(5, 4), (3, 4), (6, 5), (9, 11)] # printing original list print("The original list 1 is : " + str(test_list1)) print("The original list 2 is : " + str(test_list2)) # Using sorted() + set() + & operator + list comprehension # Using & operator to intersect, sorting before performing intersection res = set([tuple(sorted(ele)) for ele in test_list1]) & set( [tuple(sorted(ele)) for ele in test_list2] ) # printing result print("List after intersection : " + str(res))
#Output : The original list 1 is : [(3, 4), (5, 6), (9, 10), (4, 5)]
Python - Tuple List intersection (Order Irrespective) # Python3 code to demonstrate working of # Tuple List intersection [ Order irrespective ] # Using sorted() + set() + & operator + list comprehension # initializing lists test_list1 = [(3, 4), (5, 6), (9, 10), (4, 5)] test_list2 = [(5, 4), (3, 4), (6, 5), (9, 11)] # printing original list print("The original list 1 is : " + str(test_list1)) print("The original list 2 is : " + str(test_list2)) # Using sorted() + set() + & operator + list comprehension # Using & operator to intersect, sorting before performing intersection res = set([tuple(sorted(ele)) for ele in test_list1]) & set( [tuple(sorted(ele)) for ele in test_list2] ) # printing result print("List after intersection : " + str(res)) #Output : The original list 1 is : [(3, 4), (5, 6), (9, 10), (4, 5)] [END]
Python - Tuple List intersection (Order Irrespective)
https://www.geeksforgeeks.org/python-tuple-list-intersection-order-irrespective/
# Python3 code to demonstrate working of # Tuple List intersection [ Order irrespective ] # Using list comprehension + map() + frozenset() + & operator # initializing lists test_list1 = [(3, 4), (5, 6), (9, 10), (4, 5)] test_list2 = [(5, 4), (3, 4), (6, 5), (9, 11)] # printing original list print("The original list 1 is : " + str(test_list1)) print("The original list 2 is : " + str(test_list2)) # Using list comprehension + map() + frozenset() + & operator # frozenset used as map() requires hashable container, which # set is not, result in frozenset format res = set(map(frozenset, test_list1)) & set(map(frozenset, test_list2)) # printing result print("List after intersection : " + str(res))
#Output : The original list 1 is : [(3, 4), (5, 6), (9, 10), (4, 5)]
Python - Tuple List intersection (Order Irrespective) # Python3 code to demonstrate working of # Tuple List intersection [ Order irrespective ] # Using list comprehension + map() + frozenset() + & operator # initializing lists test_list1 = [(3, 4), (5, 6), (9, 10), (4, 5)] test_list2 = [(5, 4), (3, 4), (6, 5), (9, 11)] # printing original list print("The original list 1 is : " + str(test_list1)) print("The original list 2 is : " + str(test_list2)) # Using list comprehension + map() + frozenset() + & operator # frozenset used as map() requires hashable container, which # set is not, result in frozenset format res = set(map(frozenset, test_list1)) & set(map(frozenset, test_list2)) # printing result print("List after intersection : " + str(res)) #Output : The original list 1 is : [(3, 4), (5, 6), (9, 10), (4, 5)] [END]
Python - Tuple List intersection (Order Irrespective)
https://www.geeksforgeeks.org/python-tuple-list-intersection-order-irrespective/
# Python3 code to demonstrate working of # Tuple List intersection [ Order irrespective ] # Using set() + frozenset() + intersection() + list comprehension # initializing lists test_list1 = [(3, 4), (5, 6), (9, 10), (4, 5)] test_list2 = [(5, 4), (3, 4), (6, 5), (9, 11)] # printing original list print("The original list 1 is : " + str(test_list1)) print("The original list 2 is : " + str(test_list2)) # Using set() + frozenset() + intersection() + list comprehension set1 = set(frozenset(ele) for ele in test_list1) set2 = set(frozenset(ele) for ele in test_list2) res = [tuple(ele) for ele in (set1 & set2)] # printing result print("List after intersection : " + str(res))
#Output : The original list 1 is : [(3, 4), (5, 6), (9, 10), (4, 5)]
Python - Tuple List intersection (Order Irrespective) # Python3 code to demonstrate working of # Tuple List intersection [ Order irrespective ] # Using set() + frozenset() + intersection() + list comprehension # initializing lists test_list1 = [(3, 4), (5, 6), (9, 10), (4, 5)] test_list2 = [(5, 4), (3, 4), (6, 5), (9, 11)] # printing original list print("The original list 1 is : " + str(test_list1)) print("The original list 2 is : " + str(test_list2)) # Using set() + frozenset() + intersection() + list comprehension set1 = set(frozenset(ele) for ele in test_list1) set2 = set(frozenset(ele) for ele in test_list2) res = [tuple(ele) for ele in (set1 & set2)] # printing result print("List after intersection : " + str(res)) #Output : The original list 1 is : [(3, 4), (5, 6), (9, 10), (4, 5)] [END]
Python - Tuple List intersection (Order Irrespective)
https://www.geeksforgeeks.org/python-tuple-list-intersection-order-irrespective/
# initializing lists test_list1 = [(3, 4), (5, 6), (9, 10), (4, 5)] test_list2 = [(5, 4), (3, 4), (6, 5), (9, 11)] # Creating an empty dictionary freq_dict = {} # Looping through the tuples in test_list1 and test_list2 for tup in test_list1 + test_list2: # Sorting the tuple and converting it to a string sorted_tup_str = str(sorted(tup)) # Checking if the string is already in freq_dict if sorted_tup_str in freq_dict: freq_dict[sorted_tup_str] += 1 else: freq_dict[sorted_tup_str] = 1 # Creating a list comprehension using the tuples that appear in both lists res = [tup for tup in test_list1 if freq_dict[str(sorted(tup))] >= 2] # Printing the resulting list print("List after intersection: " + str(res))
#Output : The original list 1 is : [(3, 4), (5, 6), (9, 10), (4, 5)]
Python - Tuple List intersection (Order Irrespective) # initializing lists test_list1 = [(3, 4), (5, 6), (9, 10), (4, 5)] test_list2 = [(5, 4), (3, 4), (6, 5), (9, 11)] # Creating an empty dictionary freq_dict = {} # Looping through the tuples in test_list1 and test_list2 for tup in test_list1 + test_list2: # Sorting the tuple and converting it to a string sorted_tup_str = str(sorted(tup)) # Checking if the string is already in freq_dict if sorted_tup_str in freq_dict: freq_dict[sorted_tup_str] += 1 else: freq_dict[sorted_tup_str] = 1 # Creating a list comprehension using the tuples that appear in both lists res = [tup for tup in test_list1 if freq_dict[str(sorted(tup))] >= 2] # Printing the resulting list print("List after intersection: " + str(res)) #Output : The original list 1 is : [(3, 4), (5, 6), (9, 10), (4, 5)] [END]
Python - Tuple List intersection (Order Irrespective)
https://www.geeksforgeeks.org/python-tuple-list-intersection-order-irrespective/
# initializing lists test_list1 = [(3, 4), (5, 6), (9, 10), (4, 5)] test_list2 = [(5, 4), (3, 4), (6, 5), (9, 11)] # Using nested loops res = [] for tup1 in test_list1: for tup2 in test_list2: if set(tup1) == set(tup2): res.append(tup1) # printing result print("List after intersection : " + str(res))
#Output : The original list 1 is : [(3, 4), (5, 6), (9, 10), (4, 5)]
Python - Tuple List intersection (Order Irrespective) # initializing lists test_list1 = [(3, 4), (5, 6), (9, 10), (4, 5)] test_list2 = [(5, 4), (3, 4), (6, 5), (9, 11)] # Using nested loops res = [] for tup1 in test_list1: for tup2 in test_list2: if set(tup1) == set(tup2): res.append(tup1) # printing result print("List after intersection : " + str(res)) #Output : The original list 1 is : [(3, 4), (5, 6), (9, 10), (4, 5)] [END]
Python - Intersection in Tuple Records data
https://www.geeksforgeeks.org/python-intersection-in-tuple-records-data/
# Python3 code to demonstrate working of # Intersection in Tuple Records Data # Using list comprehension # Initializing lists test_list1 = [("gfg", 1), ("is", 2), ("best", 3)] test_list2 = [("i", 3), ("love", 4), ("gfg", 1)] # printing original lists print("The original list 1 is : " + str(test_list1)) print("The original list 2 is : " + str(test_list2)) # Intersection in Tuple Records Data # Using list comprehension res = [ele1 for ele1 in test_list1 for ele2 in test_list2 if ele1 == ele2] # printing result print("The Intersection of data records is : " + str(res))
#Output : The original list 1 is : [('gfg', 1), ('is', 2), ('best', 3)]
Python - Intersection in Tuple Records data # Python3 code to demonstrate working of # Intersection in Tuple Records Data # Using list comprehension # Initializing lists test_list1 = [("gfg", 1), ("is", 2), ("best", 3)] test_list2 = [("i", 3), ("love", 4), ("gfg", 1)] # printing original lists print("The original list 1 is : " + str(test_list1)) print("The original list 2 is : " + str(test_list2)) # Intersection in Tuple Records Data # Using list comprehension res = [ele1 for ele1 in test_list1 for ele2 in test_list2 if ele1 == ele2] # printing result print("The Intersection of data records is : " + str(res)) #Output : The original list 1 is : [('gfg', 1), ('is', 2), ('best', 3)] [END]
Python - Intersection in Tuple Records data
https://www.geeksforgeeks.org/python-intersection-in-tuple-records-data/
# Python3 code to demonstrate working of # Intersection in Tuple Records Data # Using set.intersection() # Initializing lists test_list1 = [("gfg", 1), ("is", 2), ("best", 3)] test_list2 = [("i", 3), ("love", 4), ("gfg", 1)] # printing original lists print("The original list 1 is : " + str(test_list1)) print("The original list 2 is : " + str(test_list2)) # Intersection in Tuple Records Data # set.intersection() res = list(set(test_list1).intersection(set(test_list2))) # printing result print("The Intersection of data records is : " + str(res))
#Output : The original list 1 is : [('gfg', 1), ('is', 2), ('best', 3)]
Python - Intersection in Tuple Records data # Python3 code to demonstrate working of # Intersection in Tuple Records Data # Using set.intersection() # Initializing lists test_list1 = [("gfg", 1), ("is", 2), ("best", 3)] test_list2 = [("i", 3), ("love", 4), ("gfg", 1)] # printing original lists print("The original list 1 is : " + str(test_list1)) print("The original list 2 is : " + str(test_list2)) # Intersection in Tuple Records Data # set.intersection() res = list(set(test_list1).intersection(set(test_list2))) # printing result print("The Intersection of data records is : " + str(res)) #Output : The original list 1 is : [('gfg', 1), ('is', 2), ('best', 3)] [END]
Python - Intersection in Tuple Records data
https://www.geeksforgeeks.org/python-intersection-in-tuple-records-data/
# define the two lists of tuples list1 = [("gfg", 1), ("is", 2), ("best", 3)] list2 = [("i", 3), ("love", 4), ("gfg", 1)] # create two dictionaries from the lists dict1 = dict(list1) dict2 = dict(list2) # find the keys that are present in both dictionaries common_keys = set(dict1.keys()).intersection(set(dict2.keys())) # create a list of tuples with the common keys and their values result = [(key, dict1[key]) for key in common_keys] # print the result print("The Intersection of data records is :", result)
#Output : The original list 1 is : [('gfg', 1), ('is', 2), ('best', 3)]
Python - Intersection in Tuple Records data # define the two lists of tuples list1 = [("gfg", 1), ("is", 2), ("best", 3)] list2 = [("i", 3), ("love", 4), ("gfg", 1)] # create two dictionaries from the lists dict1 = dict(list1) dict2 = dict(list2) # find the keys that are present in both dictionaries common_keys = set(dict1.keys()).intersection(set(dict2.keys())) # create a list of tuples with the common keys and their values result = [(key, dict1[key]) for key in common_keys] # print the result print("The Intersection of data records is :", result) #Output : The original list 1 is : [('gfg', 1), ('is', 2), ('best', 3)] [END]
Python - Intersection in Tuple Records data
https://www.geeksforgeeks.org/python-intersection-in-tuple-records-data/
test_list1 = [("gfg", 1), ("is", 2), ("best", 3)] test_list2 = [("i", 3), ("love", 4), ("gfg", 1)] # printing original lists print("The original list 1 is : " + str(test_list1)) print("The original list 2 is : " + str(test_list2)) res = list(filter(lambda t: t in test_list2, test_list1)) print("The Intersection of data records is : " + str(res)) # This code is contributed by Jyothi pinjala
#Output : The original list 1 is : [('gfg', 1), ('is', 2), ('best', 3)]
Python - Intersection in Tuple Records data test_list1 = [("gfg", 1), ("is", 2), ("best", 3)] test_list2 = [("i", 3), ("love", 4), ("gfg", 1)] # printing original lists print("The original list 1 is : " + str(test_list1)) print("The original list 2 is : " + str(test_list2)) res = list(filter(lambda t: t in test_list2, test_list1)) print("The Intersection of data records is : " + str(res)) # This code is contributed by Jyothi pinjala #Output : The original list 1 is : [('gfg', 1), ('is', 2), ('best', 3)] [END]
Python - Intersection in Tuple Records data
https://www.geeksforgeeks.org/python-intersection-in-tuple-records-data/
# test data test_list1 = [("gfg", 1), ("is", 2), ("best", 3)] test_list2 = [("i", 3), ("love", 4), ("gfg", 1)] # initialize an empty list intersection = [] # loop through each tuple in test_list1 for tuple1 in test_list1: # extract the first element (string) str1 = tuple1[0] # loop through each tuple in test_list2 for tuple2 in test_list2: # extract the first element (string) str2 = tuple2[0] # if the strings match, append the tuple from test_list1 to intersection if str1 == str2: intersection.append(tuple1) # print the intersection print("The intersection of data records is:", intersection)
#Output : The original list 1 is : [('gfg', 1), ('is', 2), ('best', 3)]
Python - Intersection in Tuple Records data # test data test_list1 = [("gfg", 1), ("is", 2), ("best", 3)] test_list2 = [("i", 3), ("love", 4), ("gfg", 1)] # initialize an empty list intersection = [] # loop through each tuple in test_list1 for tuple1 in test_list1: # extract the first element (string) str1 = tuple1[0] # loop through each tuple in test_list2 for tuple2 in test_list2: # extract the first element (string) str2 = tuple2[0] # if the strings match, append the tuple from test_list1 to intersection if str1 == str2: intersection.append(tuple1) # print the intersection print("The intersection of data records is:", intersection) #Output : The original list 1 is : [('gfg', 1), ('is', 2), ('best', 3)] [END]
Python - Intersection in Tuple Records data
https://www.geeksforgeeks.org/python-intersection-in-tuple-records-data/
import itertools test_list1 = [("gfg", 1), ("is", 2), ("best", 3)] test_list2 = [("i", 3), ("love", 4), ("gfg", 1)] # use itertools.product() to create a Cartesian product of the two lists cartesian_product = list(itertools.product(test_list1, test_list2)) # use list comprehension to filter the resulting list filtered_list = [x for x in cartesian_product if x[0][0] == x[1][0]] # use list comprehension to extract the tuples that match the condition in step 3 intersection = [x[0] for x in filtered_list] # print the intersection print("The intersection of data records is:", intersection)
#Output : The original list 1 is : [('gfg', 1), ('is', 2), ('best', 3)]
Python - Intersection in Tuple Records data import itertools test_list1 = [("gfg", 1), ("is", 2), ("best", 3)] test_list2 = [("i", 3), ("love", 4), ("gfg", 1)] # use itertools.product() to create a Cartesian product of the two lists cartesian_product = list(itertools.product(test_list1, test_list2)) # use list comprehension to filter the resulting list filtered_list = [x for x in cartesian_product if x[0][0] == x[1][0]] # use list comprehension to extract the tuples that match the condition in step 3 intersection = [x[0] for x in filtered_list] # print the intersection print("The intersection of data records is:", intersection) #Output : The original list 1 is : [('gfg', 1), ('is', 2), ('best', 3)] [END]
Python - Unique Tuple Frequency (Order Irrespective)
https://www.geeksforgeeks.org/python-unique-tuple-frequency-order-irrespective/
# Python3 code to demonstrate working of # Unique Tuple Frequency [ Order Irrespective ] # Using tuple() + list comprehension + sorted() + len() # initializing lists test_list = [(3, 4), (1, 2), (4, 3), (5, 6)] # printing original list print("The original list is : " + str(test_list)) # Using tuple() + list comprehension + sorted() + len() # Size computed after conversion to set res = len(list(set(tuple(sorted(sub)) for sub in test_list))) # printing result print("Unique tuples Frequency : " + str(res))
#Output : The original list is : [(3, 4), (1, 2), (4, 3), (5, 6)]
Python - Unique Tuple Frequency (Order Irrespective) # Python3 code to demonstrate working of # Unique Tuple Frequency [ Order Irrespective ] # Using tuple() + list comprehension + sorted() + len() # initializing lists test_list = [(3, 4), (1, 2), (4, 3), (5, 6)] # printing original list print("The original list is : " + str(test_list)) # Using tuple() + list comprehension + sorted() + len() # Size computed after conversion to set res = len(list(set(tuple(sorted(sub)) for sub in test_list))) # printing result print("Unique tuples Frequency : " + str(res)) #Output : The original list is : [(3, 4), (1, 2), (4, 3), (5, 6)] [END]
Python - Unique Tuple Frequency (Order Irrespective)
https://www.geeksforgeeks.org/python-unique-tuple-frequency-order-irrespective/
# Python3 code to demonstrate working of # Unique Tuple Frequency [ Order Irrespective ] # Using map() + sorted() + tuple() + set() + len() # initializing lists test_list = [(3, 4), (1, 2), (4, 3), (5, 6)] # printing original list print("The original list is : " + str(test_list)) # Using map() + sorted() + tuple() + set() + len() # inner map used to perform sort and outer sort to # convert again in tuple format res = len(list(set(map(tuple, map(sorted, test_list))))) # printing result print("Unique tuples Frequency : " + str(res))
#Output : The original list is : [(3, 4), (1, 2), (4, 3), (5, 6)]
Python - Unique Tuple Frequency (Order Irrespective) # Python3 code to demonstrate working of # Unique Tuple Frequency [ Order Irrespective ] # Using map() + sorted() + tuple() + set() + len() # initializing lists test_list = [(3, 4), (1, 2), (4, 3), (5, 6)] # printing original list print("The original list is : " + str(test_list)) # Using map() + sorted() + tuple() + set() + len() # inner map used to perform sort and outer sort to # convert again in tuple format res = len(list(set(map(tuple, map(sorted, test_list))))) # printing result print("Unique tuples Frequency : " + str(res)) #Output : The original list is : [(3, 4), (1, 2), (4, 3), (5, 6)] [END]
Python - Unique Tuple Frequency (Order Irrespective)
https://www.geeksforgeeks.org/python-unique-tuple-frequency-order-irrespective/
def unique_tuple_frequency(test_list): # base case if len(test_list) == 0: return 0 # recursive call rest_freq = unique_tuple_frequency(test_list[1:]) # check if the first element is unique for t in test_list[1:]: if sorted(test_list[0]) == sorted(t): return rest_freq # if the first element is unique, add 1 to the frequency return rest_freq + 1 # initializing lists test_list = [(3, 4), (1, 2), (4, 3), (5, 6)] # printing original list print("The original list is :" + str(test_list)) # Using map() + sorted() + tuple() + set() + len() # inner map used to perform sort and outer sort to # convert again in tuple format res = unique_tuple_frequency(test_list) # printing result print("Unique tuples Frequency : " + str(res))
#Output : The original list is : [(3, 4), (1, 2), (4, 3), (5, 6)]
Python - Unique Tuple Frequency (Order Irrespective) def unique_tuple_frequency(test_list): # base case if len(test_list) == 0: return 0 # recursive call rest_freq = unique_tuple_frequency(test_list[1:]) # check if the first element is unique for t in test_list[1:]: if sorted(test_list[0]) == sorted(t): return rest_freq # if the first element is unique, add 1 to the frequency return rest_freq + 1 # initializing lists test_list = [(3, 4), (1, 2), (4, 3), (5, 6)] # printing original list print("The original list is :" + str(test_list)) # Using map() + sorted() + tuple() + set() + len() # inner map used to perform sort and outer sort to # convert again in tuple format res = unique_tuple_frequency(test_list) # printing result print("Unique tuples Frequency : " + str(res)) #Output : The original list is : [(3, 4), (1, 2), (4, 3), (5, 6)] [END]
Python - Skew Nested Tuple Summation
https://www.geeksforgeeks.org/python-skew-nested-tuple-summation/
# Python3 code to demonstrate working of # Skew Nested Tuple Summation # Using infinite loop # initializing tuple test_tup = (5, (6, (1, (9, (10, None))))) # printing original tuple print("The original tuple is : " + str(test_tup)) res = 0 while test_tup: res += test_tup[0] # assigning inner tuple as original test_tup = test_tup[1] # printing result print("Summation of 1st positions : " + str(res))
#Output : The original tuple is : (5, (6, (1, (9, (10, None)))))
Python - Skew Nested Tuple Summation # Python3 code to demonstrate working of # Skew Nested Tuple Summation # Using infinite loop # initializing tuple test_tup = (5, (6, (1, (9, (10, None))))) # printing original tuple print("The original tuple is : " + str(test_tup)) res = 0 while test_tup: res += test_tup[0] # assigning inner tuple as original test_tup = test_tup[1] # printing result print("Summation of 1st positions : " + str(res)) #Output : The original tuple is : (5, (6, (1, (9, (10, None))))) [END]
Python - Skew Nested Tuple Summation
https://www.geeksforgeeks.org/python-skew-nested-tuple-summation/
# Python3 code to demonstrate working of # Skew Nested Tuple Summation # Using recursion # helper function to perform task def tup_sum(test_tup): # return on None if not test_tup: return 0 else: return test_tup[0] + tup_sum(test_tup[1]) # initializing tuple test_tup = (5, (6, (1, (9, (10, None))))) # printing original tuple print("The original tuple is : " + str(test_tup)) # calling fnc. res = tup_sum(test_tup) # printing result print("Summation of 1st positions : " + str(res))
#Output : The original tuple is : (5, (6, (1, (9, (10, None)))))
Python - Skew Nested Tuple Summation # Python3 code to demonstrate working of # Skew Nested Tuple Summation # Using recursion # helper function to perform task def tup_sum(test_tup): # return on None if not test_tup: return 0 else: return test_tup[0] + tup_sum(test_tup[1]) # initializing tuple test_tup = (5, (6, (1, (9, (10, None))))) # printing original tuple print("The original tuple is : " + str(test_tup)) # calling fnc. res = tup_sum(test_tup) # printing result print("Summation of 1st positions : " + str(res)) #Output : The original tuple is : (5, (6, (1, (9, (10, None))))) [END]
Python - Skew Nested Tuple Summation
https://www.geeksforgeeks.org/python-skew-nested-tuple-summation/
def tup_sum(test_tup): # Base case: return 0 for empty tuple or tuple with no integer elements if not test_tup or not isinstance(test_tup[0], int): return 0 else: # Recursively compute sum of first element of current tuple and remaining tuples return test_tup[0] + tup_sum(test_tup[1:]) # Example tuple test_tup = (5, (6, (1, (9, (10, None))))) # Print original tuple print("The original tuple is:", test_tup) # Compute sum of first elements res = tup_sum(test_tup) # Print result print("Sum of first elements:", res)
#Output : The original tuple is : (5, (6, (1, (9, (10, None)))))
Python - Skew Nested Tuple Summation def tup_sum(test_tup): # Base case: return 0 for empty tuple or tuple with no integer elements if not test_tup or not isinstance(test_tup[0], int): return 0 else: # Recursively compute sum of first element of current tuple and remaining tuples return test_tup[0] + tup_sum(test_tup[1:]) # Example tuple test_tup = (5, (6, (1, (9, (10, None))))) # Print original tuple print("The original tuple is:", test_tup) # Compute sum of first elements res = tup_sum(test_tup) # Print result print("Sum of first elements:", res) #Output : The original tuple is : (5, (6, (1, (9, (10, None))))) [END]
Python - Skew Nested Tuple Summation
https://www.geeksforgeeks.org/python-skew-nested-tuple-summation/
# Python3 code to demonstrate working of # Skew Nested Tuple Summation # Using stack # initializing tuple test_tup = (5, (6, (1, (9, (10, None))))) # function to compute sum of first elements using stack def sum_first_elements(test_tup): stack = [] res = 0 stack.append(test_tup) while stack: curr = stack.pop() if isinstance(curr, int): res += curr elif curr: stack.append(curr[1]) stack.append(curr[0]) return res # printing original tuple print("The original tuple is : " + str(test_tup)) # printing result print("Summation of 1st positions : " + str(sum_first_elements(test_tup)))
#Output : The original tuple is : (5, (6, (1, (9, (10, None)))))
Python - Skew Nested Tuple Summation # Python3 code to demonstrate working of # Skew Nested Tuple Summation # Using stack # initializing tuple test_tup = (5, (6, (1, (9, (10, None))))) # function to compute sum of first elements using stack def sum_first_elements(test_tup): stack = [] res = 0 stack.append(test_tup) while stack: curr = stack.pop() if isinstance(curr, int): res += curr elif curr: stack.append(curr[1]) stack.append(curr[0]) return res # printing original tuple print("The original tuple is : " + str(test_tup)) # printing result print("Summation of 1st positions : " + str(sum_first_elements(test_tup))) #Output : The original tuple is : (5, (6, (1, (9, (10, None))))) [END]
Python - Convert Binary tuple to Integer
https://www.geeksforgeeks.org/python-convert-binary-tuple-to-integer/
# Python3 code to demonstrate working of # Convert Binary tuple to Integer # Using join() + list comprehension + int() # initializing tuple test_tup = (1, 1, 0, 1, 0, 0, 1) # printing original tuple print("The original tuple is : " + str(test_tup)) # using int() with base to get actual number res = int("".join(str(ele) for ele in test_tup), 2) # printing result print("Decimal number is : " + str(res))
#Input : test_tup = (1, 1, 0) #Output : 6
Python - Convert Binary tuple to Integer # Python3 code to demonstrate working of # Convert Binary tuple to Integer # Using join() + list comprehension + int() # initializing tuple test_tup = (1, 1, 0, 1, 0, 0, 1) # printing original tuple print("The original tuple is : " + str(test_tup)) # using int() with base to get actual number res = int("".join(str(ele) for ele in test_tup), 2) # printing result print("Decimal number is : " + str(res)) #Input : test_tup = (1, 1, 0) #Output : 6 [END]
Python - Convert Binary tuple to Integer
https://www.geeksforgeeks.org/python-convert-binary-tuple-to-integer/
# Python3 code to demonstrate working of # Convert Binary tuple to Integer # Using bit shift and | operator # initializing tuple test_tup = (1, 1, 0, 1, 0, 0, 1) # printing original tuple print("The original tuple is : " + str(test_tup)) res = 0 for ele in test_tup: # left bit shift and or operator # for intermediate addition res = (res << 1) | ele # printing result print("Decimal number is : " + str(res))
#Input : test_tup = (1, 1, 0) #Output : 6
Python - Convert Binary tuple to Integer # Python3 code to demonstrate working of # Convert Binary tuple to Integer # Using bit shift and | operator # initializing tuple test_tup = (1, 1, 0, 1, 0, 0, 1) # printing original tuple print("The original tuple is : " + str(test_tup)) res = 0 for ele in test_tup: # left bit shift and or operator # for intermediate addition res = (res << 1) | ele # printing result print("Decimal number is : " + str(res)) #Input : test_tup = (1, 1, 0) #Output : 6 [END]
Python - Convert Binary tuple to Integer
https://www.geeksforgeeks.org/python-convert-binary-tuple-to-integer/
# Python3 code to demonstrate working of # Convert Binary tuple to Integer # initializing tuple test_tup = (1, 1, 0, 1, 0, 0, 1) # printing original tuple print("The original tuple is : " + str(test_tup)) # using int() with base to get actual number x = list(map(str, test_tup)) x = "".join(x) res = int(x, 2) # printing result print("Decimal number is : " + str(res))
#Input : test_tup = (1, 1, 0) #Output : 6
Python - Convert Binary tuple to Integer # Python3 code to demonstrate working of # Convert Binary tuple to Integer # initializing tuple test_tup = (1, 1, 0, 1, 0, 0, 1) # printing original tuple print("The original tuple is : " + str(test_tup)) # using int() with base to get actual number x = list(map(str, test_tup)) x = "".join(x) res = int(x, 2) # printing result print("Decimal number is : " + str(res)) #Input : test_tup = (1, 1, 0) #Output : 6 [END]
Python - Convert Binary tuple to Integer
https://www.geeksforgeeks.org/python-convert-binary-tuple-to-integer/
# Python3 code to demonstrate working of # Convert Binary tuple to Integer # initializing tuple test_tup = (1, 1, 0, 1, 0, 0, 1) # printing original tuple print("The original tuple is : " + str(test_tup)) res = 0 j = 0 for i in range(len(test_tup), 0, -1): x = 2**j res += x * test_tup[i - 1] if j > len(test_tup): break j += 1 # printing result print("Decimal number is : " + str(res))
#Input : test_tup = (1, 1, 0) #Output : 6
Python - Convert Binary tuple to Integer # Python3 code to demonstrate working of # Convert Binary tuple to Integer # initializing tuple test_tup = (1, 1, 0, 1, 0, 0, 1) # printing original tuple print("The original tuple is : " + str(test_tup)) res = 0 j = 0 for i in range(len(test_tup), 0, -1): x = 2**j res += x * test_tup[i - 1] if j > len(test_tup): break j += 1 # printing result print("Decimal number is : " + str(res)) #Input : test_tup = (1, 1, 0) #Output : 6 [END]
Python - Convert Binary tuple to Integer
https://www.geeksforgeeks.org/python-convert-binary-tuple-to-integer/
binary_tuple = (1, 1, 0) result = 0 length = len(binary_tuple) for i in range(length): element = binary_tuple[length - i - 1] result = result + element * pow(2, i) print("The output integer is:", result)
#Input : test_tup = (1, 1, 0) #Output : 6
Python - Convert Binary tuple to Integer binary_tuple = (1, 1, 0) result = 0 length = len(binary_tuple) for i in range(length): element = binary_tuple[length - i - 1] result = result + element * pow(2, i) print("The output integer is:", result) #Input : test_tup = (1, 1, 0) #Output : 6 [END]
Python - Convert Binary tuple to Integer
https://www.geeksforgeeks.org/python-convert-binary-tuple-to-integer/
# initializing tuple test_tup = (1, 1, 0, 1, 0, 0, 1) # printing original tuple print("The original tuple is : " + str(test_tup)) # using bit shifting and bitwise operations to get actual number res = 0 for bit in test_tup: res = (res << 1) | bit # printing result print("Decimal number is : " + str(res))
#Input : test_tup = (1, 1, 0) #Output : 6
Python - Convert Binary tuple to Integer # initializing tuple test_tup = (1, 1, 0, 1, 0, 0, 1) # printing original tuple print("The original tuple is : " + str(test_tup)) # using bit shifting and bitwise operations to get actual number res = 0 for bit in test_tup: res = (res << 1) | bit # printing result print("Decimal number is : " + str(res)) #Input : test_tup = (1, 1, 0) #Output : 6 [END]
Python - Convert Binary tuple to Integer
https://www.geeksforgeeks.org/python-convert-binary-tuple-to-integer/
def binary_tuple_to_int(binary_tup): if len(binary_tup) == 0: return 0 else: return binary_tup[0] * 2 ** (len(binary_tup) - 1) + binary_tuple_to_int( binary_tup[1:] ) # initializing tuple test_tup = (1, 1, 0, 1, 0, 0, 1) # printing original tuple print("The original tuple is : " + str(test_tup)) # calling recursive method res = binary_tuple_to_int(test_tup) # printing result print("Decimal number is : " + str(res))
#Input : test_tup = (1, 1, 0) #Output : 6
Python - Convert Binary tuple to Integer def binary_tuple_to_int(binary_tup): if len(binary_tup) == 0: return 0 else: return binary_tup[0] * 2 ** (len(binary_tup) - 1) + binary_tuple_to_int( binary_tup[1:] ) # initializing tuple test_tup = (1, 1, 0, 1, 0, 0, 1) # printing original tuple print("The original tuple is : " + str(test_tup)) # calling recursive method res = binary_tuple_to_int(test_tup) # printing result print("Decimal number is : " + str(res)) #Input : test_tup = (1, 1, 0) #Output : 6 [END]
Python - Tuple XOR operation
https://www.geeksforgeeks.org/python-tuple-xor-operation/
# Python3 code to demonstrate working of # Tuple XOR operation # using zip() + generator expression # initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Tuple XOR operation # using zip() + generator expression res = tuple(ele1 ^ ele2 for ele1, ele2 in zip(test_tup1, test_tup2)) # printing result print("The XOR tuple : " + str(res))
#Output : The original tuple 1 : (10, 4, 6, 9)
Python - Tuple XOR operation # Python3 code to demonstrate working of # Tuple XOR operation # using zip() + generator expression # initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Tuple XOR operation # using zip() + generator expression res = tuple(ele1 ^ ele2 for ele1, ele2 in zip(test_tup1, test_tup2)) # printing result print("The XOR tuple : " + str(res)) #Output : The original tuple 1 : (10, 4, 6, 9) [END]
Python - Tuple XOR operation
https://www.geeksforgeeks.org/python-tuple-xor-operation/
# Python3 code to demonstrate working of # Tuple XOR operation # using map() + xor from operator import xor # initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Tuple XOR operation # using map() + xor res = tuple(map(xor, test_tup1, test_tup2)) # printing result print("The XOR tuple : " + str(res))
#Output : The original tuple 1 : (10, 4, 6, 9)
Python - Tuple XOR operation # Python3 code to demonstrate working of # Tuple XOR operation # using map() + xor from operator import xor # initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Tuple XOR operation # using map() + xor res = tuple(map(xor, test_tup1, test_tup2)) # printing result print("The XOR tuple : " + str(res)) #Output : The original tuple 1 : (10, 4, 6, 9) [END]
Python - Tuple XOR operation
https://www.geeksforgeeks.org/python-tuple-xor-operation/
# Python3 code to demonstrate working of # Tuple XOR operation # using numpy import numpy as np # initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Tuple XOR operation # using numpy res = np.bitwise_xor(test_tup1, test_tup2) # printing result print("The XOR tuple : " + str(tuple(res)))
#Output : The original tuple 1 : (10, 4, 6, 9)
Python - Tuple XOR operation # Python3 code to demonstrate working of # Tuple XOR operation # using numpy import numpy as np # initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Tuple XOR operation # using numpy res = np.bitwise_xor(test_tup1, test_tup2) # printing result print("The XOR tuple : " + str(tuple(res))) #Output : The original tuple 1 : (10, 4, 6, 9) [END]
Python - Tuple XOR operation
https://www.geeksforgeeks.org/python-tuple-xor-operation/
# Python3 code to demonstrate working of # Tuple XOR operation # initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Tuple XOR operation res = [] for i in range(0, len(test_tup1)): res.append(test_tup1[i] ^ test_tup2[i]) res = tuple(res) # printing result print("The XOR tuple : " + str(res))
#Output : The original tuple 1 : (10, 4, 6, 9)
Python - Tuple XOR operation # Python3 code to demonstrate working of # Tuple XOR operation # initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Tuple XOR operation res = [] for i in range(0, len(test_tup1)): res.append(test_tup1[i] ^ test_tup2[i]) res = tuple(res) # printing result print("The XOR tuple : " + str(res)) #Output : The original tuple 1 : (10, 4, 6, 9) [END]
Python - Tuple XOR operation
https://www.geeksforgeeks.org/python-tuple-xor-operation/
# initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # perform XOR operation using list comprehension res = tuple([test_tup1[i] ^ test_tup2[i] for i in range(len(test_tup1))]) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # print the result print("The XOR tuple : " + str(res))
#Output : The original tuple 1 : (10, 4, 6, 9)
Python - Tuple XOR operation # initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # perform XOR operation using list comprehension res = tuple([test_tup1[i] ^ test_tup2[i] for i in range(len(test_tup1))]) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # print the result print("The XOR tuple : " + str(res)) #Output : The original tuple 1 : (10, 4, 6, 9) [END]
Python - Tuple XOR operation
https://www.geeksforgeeks.org/python-tuple-xor-operation/
import operator import itertools test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # Tuple XOR operation using itertools.starmap() and operator.xor() res = tuple(itertools.starmap(operator.xor, zip(test_tup1, test_tup2))) # printing result print("The XOR tuple : " + str(res))
#Output : The original tuple 1 : (10, 4, 6, 9)
Python - Tuple XOR operation import operator import itertools test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # Tuple XOR operation using itertools.starmap() and operator.xor() res = tuple(itertools.starmap(operator.xor, zip(test_tup1, test_tup2))) # printing result print("The XOR tuple : " + str(res)) #Output : The original tuple 1 : (10, 4, 6, 9) [END]
Python - Tuple XOR operation
https://www.geeksforgeeks.org/python-tuple-xor-operation/
import pandas as pd # initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # create pandas DataFrames df1 = pd.DataFrame(list(test_tup1)).T df2 = pd.DataFrame(list(test_tup2)).T # perform XOR operation res_df = df1.astype(int).apply(lambda x: x ^ df2.astype(int).iloc[0], axis=1) # convert result DataFrame to tuple res = tuple(res_df.iloc[0].tolist()) # print result print("The XOR tuple : ", res)
#Output : The original tuple 1 : (10, 4, 6, 9)
Python - Tuple XOR operation import pandas as pd # initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # create pandas DataFrames df1 = pd.DataFrame(list(test_tup1)).T df2 = pd.DataFrame(list(test_tup2)).T # perform XOR operation res_df = df1.astype(int).apply(lambda x: x ^ df2.astype(int).iloc[0], axis=1) # convert result DataFrame to tuple res = tuple(res_df.iloc[0].tolist()) # print result print("The XOR tuple : ", res) #Output : The original tuple 1 : (10, 4, 6, 9) [END]
Python - AND operation between tuples
https://www.geeksforgeeks.org/python-and-operation-between-tuples/
# Python3 code to demonstrate working of # Cross Tuple AND operation # using map() + lambda # initialize tuples test_tup1 = (10, 4, 5) test_tup2 = (2, 5, 18) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Cross Tuple AND operation # using map() + lambda res = tuple(map(lambda i, j: i & j, test_tup1, test_tup2)) # printing result print("Resultant tuple after AND operation : " + str(res))
#Output : The original tuple 1 : (10, 4, 5)
Python - AND operation between tuples # Python3 code to demonstrate working of # Cross Tuple AND operation # using map() + lambda # initialize tuples test_tup1 = (10, 4, 5) test_tup2 = (2, 5, 18) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Cross Tuple AND operation # using map() + lambda res = tuple(map(lambda i, j: i & j, test_tup1, test_tup2)) # printing result print("Resultant tuple after AND operation : " + str(res)) #Output : The original tuple 1 : (10, 4, 5) [END]
Python - AND operation between tuples
https://www.geeksforgeeks.org/python-and-operation-between-tuples/
# Python3 code to demonstrate working of # Cross Tuple AND operation # using map() + iand() import operator # initialize tuples test_tup1 = (10, 4, 5) test_tup2 = (2, 5, 18) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Cross Tuple AND operation # using map() + iand() res = tuple(map(operator.iand, test_tup1, test_tup2)) # printing result print("Resultant tuple after AND operation : " + str(res))
#Output : The original tuple 1 : (10, 4, 5)
Python - AND operation between tuples # Python3 code to demonstrate working of # Cross Tuple AND operation # using map() + iand() import operator # initialize tuples test_tup1 = (10, 4, 5) test_tup2 = (2, 5, 18) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Cross Tuple AND operation # using map() + iand() res = tuple(map(operator.iand, test_tup1, test_tup2)) # printing result print("Resultant tuple after AND operation : " + str(res)) #Output : The original tuple 1 : (10, 4, 5) [END]
Python - AND operation between tuples
https://www.geeksforgeeks.org/python-and-operation-between-tuples/
# Python3 code to demonstrate working of # Cross Tuple AND operation # using List comprehension # initialize tuples test_tup1 = (10, 4, 5) test_tup2 = (2, 5, 18) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Cross Tuple AND operation # using List comprehension res = tuple([i & j for i, j in zip(test_tup1, test_tup2)]) # printing result print("Resultant tuple after AND operation : " + str(res)) # This code is contributed by Edula Vinay Kumar Reddy
#Output : The original tuple 1 : (10, 4, 5)
Python - AND operation between tuples # Python3 code to demonstrate working of # Cross Tuple AND operation # using List comprehension # initialize tuples test_tup1 = (10, 4, 5) test_tup2 = (2, 5, 18) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Cross Tuple AND operation # using List comprehension res = tuple([i & j for i, j in zip(test_tup1, test_tup2)]) # printing result print("Resultant tuple after AND operation : " + str(res)) # This code is contributed by Edula Vinay Kumar Reddy #Output : The original tuple 1 : (10, 4, 5) [END]
Python - AND operation between tuples
https://www.geeksforgeeks.org/python-and-operation-between-tuples/
test_tup1 = (10, 4, 5) test_tup2 = (2, 5, 18) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) res = tuple([i & j for i, j in zip(test_tup1, test_tup2)]) print(res) # This code is contributed by Jyothi pinjala
#Output : The original tuple 1 : (10, 4, 5)
Python - AND operation between tuples test_tup1 = (10, 4, 5) test_tup2 = (2, 5, 18) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) res = tuple([i & j for i, j in zip(test_tup1, test_tup2)]) print(res) # This code is contributed by Jyothi pinjala #Output : The original tuple 1 : (10, 4, 5) [END]
Python - AND operation between tuples
https://www.geeksforgeeks.org/python-and-operation-between-tuples/
def bitwise_and_tuples(tup1, tup2): result = [] for i in range(len(tup1)): result.append(tup1[i] & tup2[i]) return tuple(result) test_tup1 = (10, 4, 5) test_tup2 = (2, 5, 18) res = bitwise_and_tuples(test_tup1, test_tup2) print(res)
#Output : The original tuple 1 : (10, 4, 5)
Python - AND operation between tuples def bitwise_and_tuples(tup1, tup2): result = [] for i in range(len(tup1)): result.append(tup1[i] & tup2[i]) return tuple(result) test_tup1 = (10, 4, 5) test_tup2 = (2, 5, 18) res = bitwise_and_tuples(test_tup1, test_tup2) print(res) #Output : The original tuple 1 : (10, 4, 5) [END]
Python - Elementwise AND in tuples
https://www.geeksforgeeks.org/python-elementwise-and-in-tuples/
# Python3 code to demonstrate working of # Elementwise AND in tuples # using zip() + generator expression # initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Elementwise AND in tuples # using zip() + generator expression res = tuple(ele1 & ele2 for ele1, ele2 in zip(test_tup1, test_tup2)) # printing result print("The AND tuple : " + str(res))
#Output : The original tuple 1 : (10, 4, 6, 9)
Python - Elementwise AND in tuples # Python3 code to demonstrate working of # Elementwise AND in tuples # using zip() + generator expression # initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Elementwise AND in tuples # using zip() + generator expression res = tuple(ele1 & ele2 for ele1, ele2 in zip(test_tup1, test_tup2)) # printing result print("The AND tuple : " + str(res)) #Output : The original tuple 1 : (10, 4, 6, 9) [END]
Python - Elementwise AND in tuples
https://www.geeksforgeeks.org/python-elementwise-and-in-tuples/
# Python3 code to demonstrate working of # Elementwise AND in tuples # using map() + iand from operator import iand # initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Elementwise AND in tuples # using map() + iand res = tuple(map(iand, test_tup1, test_tup2)) # printing result print("The AND tuple : " + str(res))
#Output : The original tuple 1 : (10, 4, 6, 9)
Python - Elementwise AND in tuples # Python3 code to demonstrate working of # Elementwise AND in tuples # using map() + iand from operator import iand # initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Elementwise AND in tuples # using map() + iand res = tuple(map(iand, test_tup1, test_tup2)) # printing result print("The AND tuple : " + str(res)) #Output : The original tuple 1 : (10, 4, 6, 9) [END]
Python - Elementwise AND in tuples
https://www.geeksforgeeks.org/python-elementwise-and-in-tuples/
# Python3 code to demonstrate working of # Elementwise AND in tuples # using numpy.bitwise_and import numpy as np # initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Elementwise AND in tuples # using numpy.bitwise_and res = tuple(np.bitwise_and(np.array(test_tup1), np.array(test_tup2))) # printing result print("The AND tuple : " + str(res)) # This code is contributed by Edula Vinay Kumar Reddy
#Output : The original tuple 1 : (10, 4, 6, 9)
Python - Elementwise AND in tuples # Python3 code to demonstrate working of # Elementwise AND in tuples # using numpy.bitwise_and import numpy as np # initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Elementwise AND in tuples # using numpy.bitwise_and res = tuple(np.bitwise_and(np.array(test_tup1), np.array(test_tup2))) # printing result print("The AND tuple : " + str(res)) # This code is contributed by Edula Vinay Kumar Reddy #Output : The original tuple 1 : (10, 4, 6, 9) [END]
Python - Elementwise AND in tuples
https://www.geeksforgeeks.org/python-elementwise-and-in-tuples/
# Initialize input tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # Perform elementwise AND operation using a list comprehension and bitwise & res = tuple(test_tup1[i] & test_tup2[i] for i in range(len(test_tup1))) # Print the resulting tuple print("The AND tuple: " + str(res))
#Output : The original tuple 1 : (10, 4, 6, 9)
Python - Elementwise AND in tuples # Initialize input tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) # Perform elementwise AND operation using a list comprehension and bitwise & res = tuple(test_tup1[i] & test_tup2[i] for i in range(len(test_tup1))) # Print the resulting tuple print("The AND tuple: " + str(res)) #Output : The original tuple 1 : (10, 4, 6, 9) [END]
Python - Elementwise AND in tuples
https://www.geeksforgeeks.org/python-elementwise-and-in-tuples/
test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) and_tuple = () for i in range(len(test_tup1)): and_tuple += ((test_tup1[i] & test_tup2[i]),) print("The AND tuple:", and_tuple)
#Output : The original tuple 1 : (10, 4, 6, 9)
Python - Elementwise AND in tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3) and_tuple = () for i in range(len(test_tup1)): and_tuple += ((test_tup1[i] & test_tup2[i]),) print("The AND tuple:", and_tuple) #Output : The original tuple 1 : (10, 4, 6, 9) [END]
Python | Sort Python Dictionaries by Key or Value
https://www.geeksforgeeks.org/python-sort-python-dictionaries-by-key-or-value/
myDict = {"ravi": 10, "rajnish": 9, "sanjeev": 15, "yash": 2, "suraj": 32} myKeys = list(myDict.keys()) myKeys.sort() sorted_dict = {i: myDict[i] for i in myKeys} print(sorted_dict)
Input: {'ravi': 10, 'rajnish': 9, 'sanjeev': 15, 'yash': 2, 'suraj': 32}
Python | Sort Python Dictionaries by Key or Value myDict = {"ravi": 10, "rajnish": 9, "sanjeev": 15, "yash": 2, "suraj": 32} myKeys = list(myDict.keys()) myKeys.sort() sorted_dict = {i: myDict[i] for i in myKeys} print(sorted_dict) Input: {'ravi': 10, 'rajnish': 9, 'sanjeev': 15, 'yash': 2, 'suraj': 32} [END]
Python | Sort Python Dictionaries by Key or Value
https://www.geeksforgeeks.org/python-sort-python-dictionaries-by-key-or-value/
# Function calling def dictionary(): # Declare hash function key_value = {} # Initializing value key_value[2] = 56 key_value[1] = 2 key_value[5] = 12 key_value[4] = 24 key_value[6] = 18 key_value[3] = 323 print("Task 1:-\n") print("key_value", key_value) # iterkeys() returns an iterator over the # dictionary?????????s keys. for i in sorted(key_value.keys()): print(i" ") def main(): # function calling dictionairy() # Main function calling if __name__ == "__main__": main()
Input: {'ravi': 10, 'rajnish': 9, 'sanjeev': 15, 'yash': 2, 'suraj': 32}
Python | Sort Python Dictionaries by Key or Value # Function calling def dictionary(): # Declare hash function key_value = {} # Initializing value key_value[2] = 56 key_value[1] = 2 key_value[5] = 12 key_value[4] = 24 key_value[6] = 18 key_value[3] = 323 print("Task 1:-\n") print("key_value", key_value) # iterkeys() returns an iterator over the # dictionary?????????s keys. for i in sorted(key_value.keys()): print(i" ") def main(): # function calling dictionairy() # Main function calling if __name__ == "__main__": main() Input: {'ravi': 10, 'rajnish': 9, 'sanjeev': 15, 'yash': 2, 'suraj': 32} [END]
Python | Sort Python Dictionaries by Key or Value
https://www.geeksforgeeks.org/python-sort-python-dictionaries-by-key-or-value/
# Creates a sorted dictionary (sorted by key) from collections import OrderedDict dict = {"ravi": "10", "rajnish": "9", "sanjeev": "15", "yash": "2", "suraj": "32"} dict1 = OrderedDict(sorted(dict.items())) print(dict1)
Input: {'ravi': 10, 'rajnish': 9, 'sanjeev': 15, 'yash': 2, 'suraj': 32}
Python | Sort Python Dictionaries by Key or Value # Creates a sorted dictionary (sorted by key) from collections import OrderedDict dict = {"ravi": "10", "rajnish": "9", "sanjeev": "15", "yash": "2", "suraj": "32"} dict1 = OrderedDict(sorted(dict.items())) print(dict1) Input: {'ravi': 10, 'rajnish': 9, 'sanjeev': 15, 'yash': 2, 'suraj': 32} [END]
Python | Sort Python Dictionaries by Key or Value
https://www.geeksforgeeks.org/python-sort-python-dictionaries-by-key-or-value/
# function calling def dictionairy(): # Declaring the hash function key_value = {} # Initialize value key_value[2] = 56 key_value[1] = 2 key_value[5] = 12 key_value[4] = 24 key_value[6] = 18 key_value[3] = 323 print("key_value", key_value) print("Task 2:-\nKeys and Values sorted in", "alphabetical order by the key ") # sorted(key_value) returns an iterator over the # Dictionary?????????s value sorted in keys. for i in sorted(key_value): print((i, key_value[i])" ") def main(): # function calling dictionairy() # main function calling if __name__ == "__main__": main()
Input: {'ravi': 10, 'rajnish': 9, 'sanjeev': 15, 'yash': 2, 'suraj': 32}
Python | Sort Python Dictionaries by Key or Value # function calling def dictionairy(): # Declaring the hash function key_value = {} # Initialize value key_value[2] = 56 key_value[1] = 2 key_value[5] = 12 key_value[4] = 24 key_value[6] = 18 key_value[3] = 323 print("key_value", key_value) print("Task 2:-\nKeys and Values sorted in", "alphabetical order by the key ") # sorted(key_value) returns an iterator over the # Dictionary?????????s value sorted in keys. for i in sorted(key_value): print((i, key_value[i])" ") def main(): # function calling dictionairy() # main function calling if __name__ == "__main__": main() Input: {'ravi': 10, 'rajnish': 9, 'sanjeev': 15, 'yash': 2, 'suraj': 32} [END]
Python | Sort Python Dictionaries by Key or Value
https://www.geeksforgeeks.org/python-sort-python-dictionaries-by-key-or-value/
# Function calling def dictionairy(): # Declaring hash function key_value = {} # Initializing the value key_value[2] = 56 key_value[1] = 2 key_value[5] = 12 key_value[4] = 24 key_value[6] = 18 key_value[3] = 323 print("key_value", key_value) print("Task 3:-\nKeys and Values sorted", "in alphabetical order by the value") # Note that it will sort in lexicographical order # For mathematical way, change it to float print(sorted(key_value.items(), key=lambda kv: (kv[1], kv[0]))) def main(): # function calling dictionairy() # main function calling if __name__ == "__main__": main()
Input: {'ravi': 10, 'rajnish': 9, 'sanjeev': 15, 'yash': 2, 'suraj': 32}
Python | Sort Python Dictionaries by Key or Value # Function calling def dictionairy(): # Declaring hash function key_value = {} # Initializing the value key_value[2] = 56 key_value[1] = 2 key_value[5] = 12 key_value[4] = 24 key_value[6] = 18 key_value[3] = 323 print("key_value", key_value) print("Task 3:-\nKeys and Values sorted", "in alphabetical order by the value") # Note that it will sort in lexicographical order # For mathematical way, change it to float print(sorted(key_value.items(), key=lambda kv: (kv[1], kv[0]))) def main(): # function calling dictionairy() # main function calling if __name__ == "__main__": main() Input: {'ravi': 10, 'rajnish': 9, 'sanjeev': 15, 'yash': 2, 'suraj': 32} [END]
Python | Sort Python Dictionaries by Key or Value
https://www.geeksforgeeks.org/python-sort-python-dictionaries-by-key-or-value/
# Creates a sorted dictionary (sorted by key) from collections import OrderedDict import numpy as np dict = {"ravi": 10, "rajnish": 9, "sanjeev": 15, "yash": 2, "suraj": 32} print(dict) keys = list(dict.keys()) values = list(dict.values()) sorted_value_index = np.argsort(values) sorted_dict = {keys[i]: values[i] for i in sorted_value_index} print(sorted_dict)
Input: {'ravi': 10, 'rajnish': 9, 'sanjeev': 15, 'yash': 2, 'suraj': 32}
Python | Sort Python Dictionaries by Key or Value # Creates a sorted dictionary (sorted by key) from collections import OrderedDict import numpy as np dict = {"ravi": 10, "rajnish": 9, "sanjeev": 15, "yash": 2, "suraj": 32} print(dict) keys = list(dict.keys()) values = list(dict.values()) sorted_value_index = np.argsort(values) sorted_dict = {keys[i]: values[i] for i in sorted_value_index} print(sorted_dict) Input: {'ravi': 10, 'rajnish': 9, 'sanjeev': 15, 'yash': 2, 'suraj': 32} [END]
Handling missing keys in Python dictionaries
https://www.geeksforgeeks.org/handling-missing-keys-python-dictionaries/
# Python code to demonstrate Dictionary and # missing value error # initializing Dictionary d = {"a": 1, "b": 2} # trying to output value of absent key print("The value associated with 'c' is : ") print(d["c"])
#Output : Traceback (most recent call last):
Handling missing keys in Python dictionaries # Python code to demonstrate Dictionary and # missing value error # initializing Dictionary d = {"a": 1, "b": 2} # trying to output value of absent key print("The value associated with 'c' is : ") print(d["c"]) #Output : Traceback (most recent call last): [END]
Handling missing keys in Python dictionaries
https://www.geeksforgeeks.org/handling-missing-keys-python-dictionaries/
country_code = {"India": "0091", "Australia": "0025", "Nepal": "00977"} # search dictionary for country code of India print(country_code.get("India", "Not Found")) # search dictionary for country code of Japan print(country_code.get("Japan", "Not Found"))
#Output : Traceback (most recent call last):
Handling missing keys in Python dictionaries country_code = {"India": "0091", "Australia": "0025", "Nepal": "00977"} # search dictionary for country code of India print(country_code.get("India", "Not Found")) # search dictionary for country code of Japan print(country_code.get("Japan", "Not Found")) #Output : Traceback (most recent call last): [END]
Handling missing keys in Python dictionaries
https://www.geeksforgeeks.org/handling-missing-keys-python-dictionaries/
country_code = {"India": "0091", "Australia": "0025", "Nepal": "00977"} # Set a default value for Japan country_code.setdefault("Japan", "Not Present") # search dictionary for country code of India print(country_code["India"]) # search dictionary for country code of Japan print(country_code["Japan"])
#Output : Traceback (most recent call last):
Handling missing keys in Python dictionaries country_code = {"India": "0091", "Australia": "0025", "Nepal": "00977"} # Set a default value for Japan country_code.setdefault("Japan", "Not Present") # search dictionary for country code of India print(country_code["India"]) # search dictionary for country code of Japan print(country_code["Japan"]) #Output : Traceback (most recent call last): [END]
Handling missing keys in Python dictionaries
https://www.geeksforgeeks.org/handling-missing-keys-python-dictionaries/
# Python code to demonstrate defaultdict # importing "collections" for defaultdict import collections # declaring defaultdict # sets default value 'Key Not found' to absent keys defd = collections.defaultdict(lambda: "Key Not found") # initializing values defd["a"] = 1 # initializing values defd["b"] = 2 # printing value print("The value associated with 'a' is : ", end="") print(defd["a"]) # printing value associated with 'c' print("The value associated with 'c' is : ", end="") print(defd["c"])
#Output : Traceback (most recent call last):
Handling missing keys in Python dictionaries # Python code to demonstrate defaultdict # importing "collections" for defaultdict import collections # declaring defaultdict # sets default value 'Key Not found' to absent keys defd = collections.defaultdict(lambda: "Key Not found") # initializing values defd["a"] = 1 # initializing values defd["b"] = 2 # printing value print("The value associated with 'a' is : ", end="") print(defd["a"]) # printing value associated with 'c' print("The value associated with 'c' is : ", end="") print(defd["c"]) #Output : Traceback (most recent call last): [END]
Handling missing keys in Python dictionaries
https://www.geeksforgeeks.org/handling-missing-keys-python-dictionaries/
country_code = {"India": "0091", "Australia": "0025", "Nepal": "00977"} try: print(country_code["India"]) print(country_code["USA"]) except KeyError: print("Not Found")
#Output : Traceback (most recent call last):
Handling missing keys in Python dictionaries country_code = {"India": "0091", "Australia": "0025", "Nepal": "00977"} try: print(country_code["India"]) print(country_code["USA"]) except KeyError: print("Not Found") #Output : Traceback (most recent call last): [END]
Python dictionary with keys having multiple inputs
https://www.geeksforgeeks.org/python-dictionary-with-keys-having-multiple-inputs/
# Python code to demonstrate a dictionary # with multiple inputs in a key. import random as rn # creating an empty dictionary dict = {} # Insert first triplet in dictionary x, y, z = 10, 20, 30 dict[x, y, z] = x + y - z # Insert second triplet in dictionary x, y, z = 5, 2, 4 dict[x, y, z] = x + y - z # print the dictionary print(dict)
#Output : {(10, 20, 30): 0, (5, 2, 4): 3}
Python dictionary with keys having multiple inputs # Python code to demonstrate a dictionary # with multiple inputs in a key. import random as rn # creating an empty dictionary dict = {} # Insert first triplet in dictionary x, y, z = 10, 20, 30 dict[x, y, z] = x + y - z # Insert second triplet in dictionary x, y, z = 5, 2, 4 dict[x, y, z] = x + y - z # print the dictionary print(dict) #Output : {(10, 20, 30): 0, (5, 2, 4): 3} [END]
Python dictionary with keys having multiple inputs
https://www.geeksforgeeks.org/python-dictionary-with-keys-having-multiple-inputs/
# dictionary containing longitude and latitude of places places = {("19.07'53.2", "72.54'51.0"): "Mumbai", ("28.33'34.1", "77.06'16.6"): "Delhi"} print(places) print("\n") # Traversing dictionary with multi-keys and creating # different lists from it lat = [] long = [] plc = [] for i in places: lat.append(i[0]) long.append(i[1]) plc.append(places[i[0], i[1]]) print(lat) print(long) print(plc)
#Output : {(10, 20, 30): 0, (5, 2, 4): 3}
Python dictionary with keys having multiple inputs # dictionary containing longitude and latitude of places places = {("19.07'53.2", "72.54'51.0"): "Mumbai", ("28.33'34.1", "77.06'16.6"): "Delhi"} print(places) print("\n") # Traversing dictionary with multi-keys and creating # different lists from it lat = [] long = [] plc = [] for i in places: lat.append(i[0]) long.append(i[1]) plc.append(places[i[0], i[1]]) print(lat) print(long) print(plc) #Output : {(10, 20, 30): 0, (5, 2, 4): 3} [END]