Python – Join Tuples if similar initial element
Last Updated :
01 Jun, 2023
Sometimes, while working with Python tuples, we can have a problem in which we need to perform concatenation of records from the similarity of initial element. This problem can have applications in data domains such as Data Science. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [(5, 6), (5, 7), (5, 8), (6, 10), (7, 13)]
Output : [(5, 6, 7, 8), (6, 10), (7, 13)]
Input : test_list = [(5, 6), (6, 7), (6, 8), (6, 10), (7, 13)]
Output : [(5, 6), (6, 7, 8, 10), (7, 13)]
Method #1 : Using loop
This is brute way in which this task can be done. In this, we create new tuple, if we find no occurrence of similar tuple values previously. Slicing is used to add rest of elements to created tuple.
Python3
test_list = [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)]
print("The original list is : " + str(test_list))
res = []
for sub in test_list:
if res and res[-1][0] == sub[0]:
res[-1].extend(sub[1:])
else:
res.append([ele for ele in sub])
res = list(map(tuple, res))
print("The extracted elements : " + str(res))
|
Output :
The original list is : [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)]
The extracted elements : [(5, 6, 7), (6, 8, 10), (7, 13)]
Time complexity: O(n) where n is the number of tuples in the list.
Auxiliary space: O(n) where n is the number of tuples in the list.
Method #2 : Using defaultdict() + loop
The combination of above functions can be used to solve this problem. The advantages it offers from above method are, that it reduces one check of initializing new key, and also works well even if similar elements are not consecutive.
Python3
from collections import defaultdict
test_list = [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)]
print("The original list is : " + str(test_list))
mapp = defaultdict(list)
for key, val in test_list:
mapp[key].append(val)
res = [(key, *val) for key, val in mapp.items()]
print("The extracted elements : " + str(res))
|
Output :
The original list is : [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)]
The extracted elements : [(5, 6, 7), (6, 8, 10), (7, 13)]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: Using for loop
Python3
test_list = [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)]
print("The original list is : " + str(test_list))
res = []
x = []
for i in test_list:
if i[0] not in x:
x.append(i[0])
for i in x:
p = []
p.append(i)
for j in test_list:
if i == j[0]:
p.append(j[1])
res.append(p)
print("The extracted elements : " + str(res))
|
Output
The original list is : [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)]
The extracted elements : [[5, 6, 7], [6, 8, 10], [7, 13]]
Time complexity: O(n^2), where n is the length of the input list test_list.
Auxiliary space: O(n), where n is the length of the input list test_list.
Method #4: using dictionary and list comprehension
step-by-step algorithm for the given approach
- Initialize an empty dictionary temp_dict to store the unique initial elements as keys and a list of corresponding second elements as values.
- Iterate through each tuple x in the given list test_list.
- If the initial element of x already exists as a key in temp_dict, then append the second element of x to the corresponding value list.
If the initial element of x does not exist as a key in temp_dict, then add the initial element as a new key and a list containing the second element as its value.
- After all tuples are processed, create a new list res by iterating through the key-value pairs of temp_dict, and joining each key with its corresponding list of values.
- Return the final list res as the result.
Python3
test_list = [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)]
print("The original list is : " + str(test_list))
temp_dict = {}
for x in test_list:
temp_dict[x[0]] = temp_dict.get(x[0], []) + list(x[1:])
res = [(k,) + tuple(v) for k, v in temp_dict.items()]
print("The extracted elements : " + str(res))
|
Output
The original list is : [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)]
The extracted elements : [(5, 6, 7), (6, 8, 10), (7, 13)]
Time Complexity:
The time complexity of the above algorithm is O(n), where n is the length of test_list. It requires one traversal of test_list and temp_dict.
Auxiliary Space:
The auxiliary space complexity of the above algorithm is O(n), where n is the length of test_list. It requires temp_dict to store the values extracted from test_list. The size of temp_dict will be proportional to the number of unique keys in test_list.
Method #5: Using itertools.groupby()
Step-by-step approach:
- Import groupby from itertools.
- Loop through the groups in test_list generated by groupby function. Group the tuples based on their first element (key=lambda x: x[0]).
- Extract the values of each group and store them in a list (values).
- Append a new tuple to the result list res that contains the key and all the values.
- Print the result.
Below is the implementation of the above approach:
Python3
from itertools import groupby
test_list = [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)]
print("The original list is : " + str(test_list))
res = []
for k, g in groupby(test_list, key=lambda x: x[0]):
values = [v for _, v in g]
res.append((k, *values))
print("The extracted elements : " + str(res))
|
Output
The original list is : [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)]
The extracted elements : [(5, 6, 7), (6, 8, 10), (7, 13)]
Time complexity: O(n log n), where n is the length of test_list because we are sorting the input list by the first element before grouping.
Auxiliary space: O(n), where n is the length of test_list because we are creating a new list to store the result.
Method #6: Using pandas
Import the pandas library.
Create a DataFrame from the list test_list, with column names “A” and “B” for the two elements in each tuple.
Group the DataFrame by column “A” and aggregate column “B” as a list for each group.
Reset the index of the resulting DataFrame.
Convert the DataFrame to a list of tuples.
Python3
test_list = [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)]
import pandas as pd
df = pd.DataFrame(test_list, columns=["A", "B"])
grouped = df.groupby("A")["B"].apply(list)
res = [tuple([k] + v) for k, v in grouped.items()]
print("The extracted elements : " + str(res))
|
OUTPUT :
The extracted elements : [(5, 6, 7), (6, 8, 10), (7, 13)]
Time complexity: O(n log n), where n is the length of test_list.
Auxiliary space: O(n), where n is the length of test_list.
Method #7 : Using recursion
Step-by-step approach:
Define a recursive function that takes the input list and an index as parameters.
Inside the function, check if the index is equal to the length of the list minus 1. If it is, return the list.
Otherwise, compare the initial element of the tuple at the current index with the initial element of the tuple at the next index.
If they are the same, concatenate the tuples and recursively call the function with the updated list and index.
If they are different, recursively call the function with the original list and the next index.
Call the recursive function with the input list and index 0.
Print the extracted elements.
Python3
def join_tuples(test_list, index):
if index == len(test_list) - 1:
return test_list
elif test_list[index][0] == test_list[index + 1][0]:
test_list[index] += test_list[index + 1][1:]
test_list.pop(index + 1)
return join_tuples(test_list, index)
else:
return join_tuples(test_list, index + 1)
test_list = [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)]
print("The original list is : " + str(test_list))
res = join_tuples(test_list, 0)
print("The extracted elements : " + str(res))
|
Output
The original list is : [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)]
The extracted elements : [(5, 6, 7), (6, 8, 10), (7, 13)]
The time complexity of this method is O(n^2) in the worst case, where n is the length of the input list.
The auxiliary space complexity is O(1) since the modifications are done in-place.
Similar Reads
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples. The below Python section contains a wide collection of Python programming examples. These Python c
11 min read
Basic Programs
How to Add Two Numbers in Python - Easy Programs
Learn easy techniques and codes to add numbers in Python. Adding numbers in Python is a very easy task, and we have provided you 7 different ways to add numbers in Python. Given two numbers num1 and num2. The task is to write a Python program to find the addition of these two numbers. Examples: Inpu
6 min read
Find Maximum of two numbers in Python
In this article, we will explore various methods to find maximum of two numbers in Python. The simplest way to find maximum of two numbers in Python is by using built-in max() function. [GFGTABS] Python a = 7 b = 3 print(max(a, b)) [/GFGTABS]Output7 Explanation: max() function compares the two numbe
2 min read
Python Program to Find the Factorial of a Number
Factorial of a non-negative integer, is multiplication of all integers smaller than or equal to n in Python. Example Simple Python program to find the factorial of a number [GFGTABS] Python # Input: An integer number num = 6 # Initialize the factorial variable to 1 factorial = 1 # Calculate the fact
3 min read
Python Program for Simple Interest
Simple interest formula is given by: Simple Interest = (P x T x R)/100 Where, P is the principal amount T is the time and R is the rate Examples: Input : P = 10000 R = 5 T = 5Output :2500.0We need to find simple interest on Rs. 10,000 at the rate of 5% for 5 units of time.Python Program for simple i
2 min read
Python Program for Compound Interest
Let us discuss the formula for compound interest. The formula to calculate compound interest annually is given by: A = P(1 + R/100) t Compound Interest = A - P Where, A is amount P is the principal amount R is the rate and T is the time spanFind Compound Interest with Python C/C++ Code # Python3 pro
3 min read
Python Program to Check Armstrong Number
Given a number x, determine whether the given number is Armstrong number or not. A positive integer of n digits is called an Armstrong number of order n (order is number of digits) if. abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + .... Example: Input : 153 Output : Yes 153 is an Armstrong nu
6 min read
Array Programs
Python Program to Find Sum of Array
Given an array of integers, find the sum of its elements. Examples: Input : arr[] = {1, 2, 3}Output : 6Explanation: 1 + 2 + 3 = 6This Python program calculates the sum of an array by iterating through each element and adding it to a running total. The sum is then returned. An example usage is provid
4 min read
Python Program to Find Largest Element in an Array
To find the largest element in an array, iterate over each element and compare it with the current largest element. If an element is greater, update the largest element. At the end of the iteration, the largest element will be found. Given an array, find the largest element in it. Input : arr[] = {1
4 min read
Python Program for Array Rotation
Here we are going to see how we can rotate array with Python code. Array Rotation: Python Program for Array Rotation ExamplePartitioning the sub arrays and reversing them Approach: Input arr[] = [1, 2, 3, 4, 5, 6, 7, 8], d = 1, size = 8 1) Reverse the entire list by swapping first and last numbers i
7 min read
Python Program for Reversal algorithm for array rotation
Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements. In this article, we will explore the Reversal Algorithm for array rotation and implement it in Python. Example Input: arr[] = [1, 2, 3, 4, 5, 6, 7] d = 2 Output: arr[] = [3, 4, 5, 6, 7, 1, 2] Rotation of the above array
2 min read
Python Program to Split the array and add the first part to the end
There is a given array and split it from a specified position, and move the first part of the array add to the end. Examples: Input : arr[] = {12, 10, 5, 6, 52, 36} k = 2 Output : arr[] = {5, 6, 52, 36, 12, 10} Explanation : Split from index 2 and first part {12, 10} add to the end .Input : arr[] =
5 min read
Python Program for Find remainder of array multiplication divided by n
Write a Python program for a given multiple numbers and a number n, the task is to print the remainder after multiplying all the numbers divided by n. Examples: Input: arr[] = {100, 10, 5, 25, 35, 14}, n = 11Output: 9Explanation: 100 x 10 x 5 x 25 x 35 x 14 = 61250000 % 11 = 9Input : arr[] = {100, 1
3 min read
Python Program to check if given array is Monotonic
Given an array A containing n integers. The task is to check whether the array is Monotonic or not. An array is monotonic if it is either monotone increasing or monotone decreasing. An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all
7 min read
List Programs
Python program to interchange first and last elements in a list
Given a list, write a Python program to swap the first and last element of the list using Python. Examples: The last element of the list can be referred to as a list[-1]. Therefore, we can simply swap list[0] with list[-1]. [GFGTABS] Python # Initialize a list my_list = [1, 2, 3, 4, 5] # Interchange
5 min read
Python Program to Swap Two Elements in a List
In this article, we will explore various methods to swap two elements in a list in Python. The simplest way to do is by using multiple assignment. Example: [GFGTABS] Python a = [10, 20, 30, 40, 50] # Swapping elements at index 0 and 4 # using multiple assignment a[0], a[4] = a[4], a[0] print(a) [/GF
2 min read
How To Find the Length of a List in Python
The length of a list refers to the number of elements in the list. There are several methods to determine the length of a list in Python. In this article, we'll explore different methods to find the length of a list. The simplest and most common way to do this is by using the len() function. Let's t
3 min read
Check if element exists in list in Python
In this article, we will explore various methods to check if element exists in list in Python. The simplest way to check for the presence of an element in a list is using the in Keyword. Example: [GFGTABS] Python a = [10, 20, 30, 40, 50] # Check if 30 exists in the list if 30 in a: print("Eleme
3 min read
Different ways to clear a list in Python
In this article, we will explore various methods to clear a list in Python. The simplest way to do is by using a loop. Using clear() MethodUsing clear() method we can remove all elements from a list. This method modifies the list in place and removes all its elements. [GFGTABS] Python a = [1, 2, 3,
2 min read
Reversing a List in Python
In this article, we are going to explore multiple ways to reverse a list. Python provides several methods to reverse a list using built-in functions and manual approaches. The simplest way to reverse a list is by using the reverse() method. Let's take an example to reverse a list using reverse() met
4 min read
Matrix Programs
Adding and Subtracting Matrices in Python
In this article, we will discuss how to add and subtract elements of the matrix in Python. Example: Suppose we have two matrices A and B. A = [[1,2],[3,4]] B = [[4,5],[6,7]] then we get A+B = [[5,7],[9,11]] A-B = [[-3,-3],[-3,-3]] Now let us try to implement this using Python 1. Adding elements of t
4 min read
Python Program to Add Two Matrices
Given two matrices X and Y, the task is to compute the sum of two matrices and then print it in Python. Examples: Input : X= [[1,2,3], [4 ,5,6], [7 ,8,9]] Y = [[9,8,7], [6,5,4], [3,2,1]] Output : result= [[10,10,10], [10,10,10], [10,10,10]]Table of Content Add Two Matrices Using for loopAdd Two Matr
4 min read
Python Program to Multiply Two Matrices
Given two matrices, we will have to create a program to multiply two matrices in Python. Example: Python Matrix Multiplication of Two-Dimension [GFGTABS] Python matrix_a = [[1, 2], [3, 4]] matrix_b = [[5, 6], [7, 8]] result = [[0, 0], [0, 0]] for i in range(2): for j in range(2): result[i][j] = (mat
5 min read
Matrix Product - Python
The task of calculating the matrix product in Python involves finding the product of all elements within a matrix or 2D list . This operation requires iterating through each element in the matrix and multiplying them together to obtain a single cumulative product. For example, given a matrix a = [[1
3 min read
Transpose a matrix in Single line in Python
Transpose of a matrix is a task we all can perform very easily in Python (Using a nested loop). But there are some interesting ways to do the same in a single line. In Python, we can implement a matrix as a nested list (a list inside a list). Each element is treated as a row of the matrix. For examp
4 min read
Python - Matrix creation of n*n
Matrices are fundamental structures in programming and are widely used in various domains including mathematics, machine learning, image processing, and simulations. Creating an nÃn matrix efficiently is an important step for these applications. This article will explore multiple ways to create such
3 min read
Python | Get Kth Column of Matrix
Sometimes, while working with Python Matrix, one can have a problem in which one needs to find the Kth column of Matrix. This is a very popular problem in Machine Learning Domain and having solution to this is useful. Let's discuss certain ways in which this problem can be solved. Method #1 : Using
6 min read
Python - Vertical Concatenation in Matrix
Given a String Matrix, perform column-wise concatenation of strings, handling variable lists lengths. Input : [["Gfg", "good"], ["is", "for"]] Output : ['Gfgis', 'goodfor'] Explanation : Column wise concatenated Strings, "Gfg" concatenated with "is", and so on. Input : [["Gfg", "good", "geeks"], ["i
3 min read
Dictionary Programs
Python - Ways to remove a key from dictionary
We are given a dictionary and our task is to remove a specific key from it. For example, if we have the dictionary d = {"a": 1, "b": 2, "c": 3}, then after removing the key "b", the output will be {'a': 1, 'c': 3}. Using pop()pop() method removes a specific key from the dictionary and returns its co
3 min read
Merging or Concatenating two Dictionaries in Python
Combining two dictionaries is a common task when working with Python, especially when we need to consolidate data from multiple sources or update existing records. For example, we may have one dictionary containing user information and another with additional details and we'd like to merge them into
2 min read
Python - Convert key-values list to flat dictionary
We are given a list that contains tuples with the pairs of key and values we need to convert that list into a flat dictionary. For example a = [("name", "Ak"), ("age", 25), ("city", "NYC")] is a list we need to convert it to dictionary so that output should be a flat dictionary {'name': 'Ak', 'age':
3 min read
Python - Insertion at the beginning in OrderedDict
Given an ordered dict, write a program to insert items in the beginning of the ordered dict. Examples: Input: original_dict = {'a':1, 'b':2} item to be inserted ('c', 3) Output: {'c':3, 'a':1, 'b':2}Input: original_dict = {'akshat':1, 'manjeet':2} item to be inserted ('nikhil', 3) Output: {'nikhil':
2 min read
Python | Check order of character in string using OrderedDict( )
Given an input string and a pattern, check if characters in the input string follows the same order as determined by characters present in the pattern. Assume there wonât be any duplicate characters in the pattern. Examples: Input: string = "engineers rock"pattern = "er";Output: trueExplanation: All
3 min read
Python dictionary with keys having multiple inputs
Prerequisite: Python-Dictionary. How to create a dictionary where a key is formed using inputs? Let us consider an example where have an equation for three input variables, x, y, and z. We want to store values of equation for different input triplets. Example 1: C/C++ Code # Python code to demonstra
4 min read
Tuple Programs
Find the size of a Tuple in Python
Tuple is a collection of Python objects much like a list. The sequence of values stored in a tuple can be of any type, and they are indexed by integers. Values of a tuple are syntactically separated by âcommasâ. Although it is not necessary, it is more common to define a tuple by closing the sequenc
2 min read
Python - Maximum and Minimum K elements in Tuple
Sometimes, while dealing with tuples, we can have problem in which we need to extract only extreme K elements, i.e maximum and minimum K elements in Tuple. This problem can have applications across domains such as web development and Data Science. Let's discuss certain ways in which this problem can
8 min read
Python program to create a list of tuples from given list having number and its cube in each tuple
Creating a list of tuples where each tuple contains a number and its cube is a common programming task. Itâs a simple but handy task that can be useful in many situations like working with data or solving math problems. In this article, weâll learn how to do this in Python by creating a list of tupl
3 min read
Python - Adding Tuple to List and vice - versa
Sometimes, while working with Python containers, we can have a problem in which we need to perform addition of one container with another. This kind of problem can have occurrence in many data domains across Computer Science and Programming. Let's discuss certain ways in which this task can be perfo
5 min read
Python - Closest Pair to Kth index element in Tuple
In the given problem, condition K specifies the maximum allowable difference between corresponding elements of tuples, i.e., it represents the proximity threshold for finding the nearest tuple. The goal is to find the tuple in the list whose elements have the smallest maximum difference compared to
7 min read
Python - Join Tuples if similar initial element
Sometimes, while working with Python tuples, we can have a problem in which we need to perform concatenation of records from the similarity of initial element. This problem can have applications in data domains such as Data Science. Let's discuss certain ways in which this task can be performed. Inp
8 min read
Searching and Sorting Programs
Python Program for Linear Search
Problem: Given an array arr[] of n elements, write a function to search a given element x in arr[] using Python. Examples: Input: arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] # Element to Find x = 'J' Output
4 min read
Python Program for Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. Python Program for Bubble SortThe provided Python code implements the Bubble Sort algorithm, which sorts an array by repeatedly comparing adjacent elements and swappi
2 min read
Python Program for Selection Sort
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. Python Program for Selection SortThe provided Python code demonstrates the S
2 min read
Python Program for Insertion Sort
Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. Python Program for Insertion SortThe insertionSort function takes an array arr as input. It first calculates the length of the array (n). If the length is 0 or 1, the function returns immediately as a
2 min read
Python Program for Recursive Insertion Sort
Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. Python Program for Recursive Insertion Sort for Iterative algorithm for insertion sortAlgorithm // Sort an arr[] of size ninsertionSort(arr, n) Loop from i = 1 to n-1. a) Pick element arr[i] and inser
4 min read
Python Program for Binary Search (Recursive and Iterative)
In a nutshell, this search algorithm takes advantage of a collection of elements that is already sorted by ignoring half of the elements after just one comparison. Compare x with the middle element.If x matches with the middle element, we return the mid index.Else if x is greater than the mid elemen
4 min read
Pattern Printing Programs