Python | Extend tuples by count of elements in tuple
Last Updated :
22 Apr, 2023
Sometimes, while working with data, we can have an application in which we need to duplicate tuple elements by the amount of element count. This is very unique application but can occur in certain cases. Let's discuss certain ways in which this task can be performed.
Method #1: Using nested loops This is the brute force method by which this task can be performed. In this, the outer loop is for iteration to each element in list and inner loop is to add the similar element equating to length of respective tuple by outer loop.
Python3
# Python3 code to demonstrate working of
# Extend tuples by count in list
# using nested loop
# initialize list of tuple
test_list = [('1', '4', '6'), ('5', '8'), ('2', '9'), ('1', )]
# printing original tuples list
print("The original list : " + str(test_list))
# Extend tuples by count in list
# using nested loop
res = []
for sub in range(len(test_list)):
for ele in range(len(test_list[sub])):
res.append(test_list[sub])
# printing result
print("The modified and extended list is : " + str(res))
OutputThe original list : [('1', '4', '6'), ('5', '8'), ('2', '9'), ('1',)]
The modified and extended list is : [('1', '4', '6'), ('1', '4', '6'), ('1', '4', '6'), ('5', '8'), ('5', '8'), ('2', '9'), ('2', '9'), ('1',)]
Time complexity: O(n^2), where n is the total number of elements in the list of tuples.
Auxiliary space: O(n), where n is the total number of elements in the result list.
Method #2 : Using loop + chain() This is yet another way in which this task can be performed. In this, we reduce one loop, inner loop and multiply the tuples into one and flatten using chain(). It may have certain overheads depending upon different cases.
Python3
# Python3 code to demonstrate working of
# Extend tuples by count in list
# using loop + chain()
from itertools import chain
# initialize list of tuple
test_list = [('1', '4', '6'), ('5', '8'), ('2', '9'), ('1', )]
# printing original tuples list
print("The original list : " + str(test_list))
# Extend tuples by count in list
# using loop + chain()
res = []
for sub in range(len(test_list)):
res.append([test_list[sub]]*len(test_list[sub]))
res1 = chain(*res)
res = list(res1)
# printing result
print("The modified and extended list is : " + str(res))
OutputThe original list : [('1', '4', '6'), ('5', '8'), ('2', '9'), ('1',)]
The modified and extended list is : [('1', '4', '6'), ('1', '4', '6'), ('1', '4', '6'), ('5', '8'), ('5', '8'), ('2', '9'), ('2', '9'), ('1',)]
Time Complexity: O(n^2) where n is the length of the list "test_list".
Auxiliary Space: O(n^2) where n is the length of the list "test_list".
Method #3 : Using * operator and extend() method
Python3
# Python3 code to demonstrate working of
# Extend tuples by count in list
# initialize list of tuple
test_list = [('1', '4', '6'), ('5', '8'), ('2', '9'), ('1', )]
# printing original tuples list
print("The original list : " + str(test_list))
# Extend tuples by count in list
# using nested loop
res = []
for i in test_list:
a = [i]*len(i)
res.extend(a)
# printing result
print("The modified and extended list is : " + str(res))
OutputThe original list : [('1', '4', '6'), ('5', '8'), ('2', '9'), ('1',)]
The modified and extended list is : [('1', '4', '6'), ('1', '4', '6'), ('1', '4', '6'), ('5', '8'), ('5', '8'), ('2', '9'), ('2', '9'), ('1',)]
Time complexity: O(n^2), where n is the number of tuples in the list. The nested loop runs for each tuple in the list and for each element in the tuple.
Auxiliary space: O(n), where n is the number of tuples in the list.
Method #4 : Using list comprehension and * operator
Python3
# Python3 code to demonstrate working of
# Extend tuples by count in list
# using list comprehension and * operator
# initialize list of tuple
test_list = [('1', '4', '6'), ('5', '8'), ('2', '9'), ('1', )]
# printing original tuples list
print("The original list : " + str(test_list))
# Extend tuples by count in list
# using list comprehension and * operator
res = [i for i in test_list for _ in range(len(i))]
# printing result
print("The modified and extended list is : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original list : [('1', '4', '6'), ('5', '8'), ('2', '9'), ('1',)]
The modified and extended list is : [('1', '4', '6'), ('1', '4', '6'), ('1', '4', '6'), ('5', '8'), ('5', '8'), ('2', '9'), ('2', '9'), ('1',)]
This method uses list comprehension to iterate through the original list and the * operator to repeat the tuple the number of times as the number of elements in the tuple. This method is more concise and more efficient than the previous methods as it only requires one pass over the original list and avoids unnecessary appending and extending.
Time complexity: O(n), where n is the number of elements in the original list.
Auxiliary space: O(n)
Method #5: Using itertools.repeat() and itertools.chain.from_iterable()
- The first step is to import the itertools module. This module provides various functions that operate on iterators to produce complex iterators.
- The next step is to initialize a list of tuples called test_list. Each tuple contains some elements. This list will be used to demonstrate the operation of the itertools module.
- After that, the original list of tuples is printed using the print() function.
- The next step is to extend the tuples in the list by their length. This can be done using the itertools.repeat() function. It takes two arguments - the first argument is the object to be repeated, and the second argument is the number of times it should be repeated.
- In this case, we want to repeat each tuple in test_list by its length. To do this, we can use a generator expression that iterates over each tuple in test_list and passes its length as the second argument to itertools.repeat(). This generator expression is passed to list() to convert it to a list.
- The itertools.chain.from_iterable() function is then used to flatten the resulting list of repeated tuples into a single list. This function takes an iterable of iterables and returns a single iterable that concatenates all the inner iterables.
- Finally, the modified and extended list is printed using the print() function.
Python3
import itertools
# initialize list of tuple
test_list = [('1', '4', '6'), ('5', '8'), ('2', '9'), ('1', )]
# printing original tuples list
print("The original list : " + str(test_list))
# Extend tuples by count in list
# using itertools.repeat() and itertools.chain.from_iterable()
res = list(itertools.chain.from_iterable(itertools.repeat(i, len(i)) for i in test_list))
# printing result
print("The modified and extended list is : " + str(res))
OutputThe original list : [('1', '4', '6'), ('5', '8'), ('2', '9'), ('1',)]
The modified and extended list is : [('1', '4', '6'), ('1', '4', '6'), ('1', '4', '6'), ('5', '8'), ('5', '8'), ('2', '9'), ('2', '9'), ('1',)]
The time complexity of this approach is O(nm), where n is the number of tuples and m is the maximum length of a tuple.
The auxiliary space complexity is also O(nm), for the resulting list of extended tuples.
Similar Reads
Python - Count elements in record tuple
Sometimes, while working with data in form of records, we can have a problem in which we need to find the total element counts of all the records received. This is a very common application that can occur in Data Science domain. Letâs discuss certain ways in which this task can be performed. Method
5 min read
Swap tuple elements in list of tuples - Python
The task of swapping tuple elements in a list of tuples in Python involves exchanging the positions of elements within each tuple while maintaining the list structure. Given a list of tuples, the goal is to swap the first and second elements in every tuple. For example, with a = [(3, 4), (6, 5), (7,
3 min read
Python - Count elements in tuple list
Sometimes, while working with data in form of records, we can have a problem in which we need to find the count of all the records received. This is a very common application that can occur in Data Science domain. Letâs discuss certain ways in which this task can be performed. Method #1: Using len()
5 min read
Python - Get Nth column elements in Tuple Strings
Yet another peculiar problem that might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This article solves the problem of extracting only the
8 min read
Python | Check if element is present in tuple of tuples
Sometimes the data that we use is in the form of tuples and often we need to look into the nested tuples as well. The common problem that this can solve is looking for missing data or na value in data preprocessing. Let's discuss certain ways in which this can be performed. Method #1: Using any() an
4 min read
Python | Count tuples occurrence in list of tuples
Many a time while developing web and desktop products in Python, we use nested lists and have several queries about how to find the count of unique tuples. Let us see how to get the count of unique tuples in the given list of tuples. Below are some ways to achieve the above task. Method #1: Using It
5 min read
Python | Combining tuples in list of tuples
Sometimes, we might have to perform certain problems related to tuples in which we need to segregate the tuple elements to combine with each element of complex tuple element( such as list ). This can have application in situations we need to combine values to form a whole. Let's discuss certain ways
7 min read
Python | Elementwise AND in tuples
Sometimes, while working with records, we can have a problem in which we may need to perform mathematical bitwise AND operation across tuples. This problem can occur in day-day programming. Letâs discuss certain ways in which this task can be performed. Method #1 : Using zip() + generator expression
5 min read
Python - Convert List of Lists to Tuple of Tuples
Sometimes, while working with Python data, we can have a problem in which we need to perform interconversion of data types. This kind of problem can occur in domains in which we need to get data in particular formats such as Machine Learning. Let us discuss certain ways in which this task can be per
8 min read
Flatten tuple of List to tuple - Python
The task of flattening a tuple of lists to a tuple in Python involves extracting and combining elements from multiple lists within a tuple into a single flattened tuple. For example, given tup = ([5, 6], [6, 7, 8, 9], [3]), the goal is to flatten it into (5, 6, 6, 7, 8, 9, 3). Using itertools.chain(
3 min read