Python | Split tuple into groups of n
Last Updated :
13 Mar, 2023
Given a tuple, the task is to divide it into smaller groups of n. Let’s discuss a few methods to accomplish a given task.
Method #1: Using enumerate and range function
Python3
ini_tuple = ( 1 , 2 , 3 , 4 , 8 , 12 , 3 , 34 ,
67 , 45 , 1 , 1 , 43 , 65 , 9 , 10 )
print ("initial list ", str (ini_tuple))
res = tuple (ini_tuple[x:x + 4 ]
for x in range ( 0 , len (ini_tuple), 4 ))
print ("resultant tuples", str (res))
|
Output:
initial list (1, 2, 3, 4, 8, 12, 3, 34, 67, 45, 1, 1, 43, 65, 9, 10) resultant tuples ((1, 2, 3, 4), (8, 12, 3, 34), (67, 45, 1, 1), (43, 65, 9, 10))
Method #2: Using enumerate and mod operator
Python3
ini_tuple = ( 1 , 2 , 3 , 4 , 8 , 12 , 3 , 34 ,
67 , 45 , 1 , 1 , 43 , 65 , 9 , 10 )
print ("initial list ", str (ini_tuple))
res = tuple (ini_tuple[n:n + 4 ] for n, i in enumerate (ini_tuple)
if n % 4 = = 0 )
print ("resultant tuples", str (res))
|
Output:
initial list (1, 2, 3, 4, 8, 12, 3, 34, 67, 45, 1, 1, 43, 65, 9, 10) resultant tuples ((1, 2, 3, 4), (8, 12, 3, 34), (67, 45, 1, 1), (43, 65, 9, 10))
Method #3: Using itertools recipes
Python3
def grouper(n, iterable):
args = [ iter (iterable)] * n
return zip ( * args)
ini_tuple = ( 1 , 2 , 3 , 4 , 8 , 12 , 3 , 34 ,
67 , 45 , 1 , 1 , 43 , 65 , 9 , 10 )
print ("initial list ", str (ini_tuple))
res = tuple (grouper( 4 , ini_tuple))
print ("resultant tuples", str (res))
|
Output:
initial list (1, 2, 3, 4, 8, 12, 3, 34, 67, 45, 1, 1, 43, 65, 9, 10) resultant tuples ((1, 2, 3, 4), (8, 12, 3, 34), (67, 45, 1, 1), (43, 65, 9, 10))
Method #4: Using zip
Here is another approach using the zip function:
Python3
ini_tuple = ( 1 , 2 , 3 , 4 , 8 , 12 , 3 , 34 , 67 , 45 , 1 , 1 , 43 , 65 , 9 , 10 )
print ( "initial list" , str (ini_tuple))
res = tuple ( zip ( * [ iter (ini_tuple)] * 4 ))
print ( "resultant tuples" , str (res))
|
Output
initial list (1, 2, 3, 4, 8, 12, 3, 34, 67, 45, 1, 1, 43, 65, 9, 10)
resultant tuples ((1, 2, 3, 4), (8, 12, 3, 34), (67, 45, 1, 1), (43, 65, 9, 10))
Time complexity: O(n)
Auxiliary Space: O(n)
Share your thoughts in the comments
Please Login to comment...