Friday, December 27, 2024
Google search engine
HomeLanguagesPython | Chunk Tuples to N

Python | Chunk Tuples to N

Sometimes, while working with data, we can have a problem in which we may need to perform chunking of tuples each of size N. This is popular in applications in which we need to supply data in chunks. Let’s discuss certain ways in which this task can be performed. 

Method #1 : Using list comprehension This is brute and shorthand method to perform this task. In this, we split the N elements at a time and construct a new tuple for them. 

Python3




# Python3 code to demonstrate working of
# Chunk Tuples to N
# using list comprehension
 
# initialize tuple
test_tup = (10, 4, 5, 6, 7, 6, 8, 3, 4)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# initialize N
N = 3
 
# Chunk Tuples to N
# using list comprehension
res = [test_tup[i : i + N] for i in range(0, len(test_tup), N)]
 
# printing result
print("The tuples after chunking are : " + str(res))


Output

The original tuple : (10, 4, 5, 6, 7, 6, 8, 3, 4)
The tuples after chunking are : [(10, 4, 5), (6, 7, 6), (8, 3, 4)]

  Method #2 : Using zip() + iter() The combination of above functions can also be used to solve this problem. In this, we use zip() to combine chunks and iter() converts to suitable format. 

Python3




# Python3 code to demonstrate working of
# Chunk Tuples to N
# using zip() + iter()
 
# initialize tuple
test_tup = (10, 4, 5, 6, 7, 6, 8, 3, 4)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# initialize N
N = 3
 
# Chunk Tuples to N
# using zip() + iter()
temp = [iter(test_tup)] * N
res = list(zip(*temp))
 
# printing result
print("The tuples after chunking are : " + str(res))


Output

The original tuple : (10, 4, 5, 6, 7, 6, 8, 3, 4)
The tuples after chunking are : [(10, 4, 5), (6, 7, 6), (8, 3, 4)]

Method #3: Using numpy

Note: Install numpy module using command “pip install numpy”

The numpy library in python provides a function called numpy.array_split() which can be used to perform chunking of tuples each of size N.

Python3




import numpy as np
 
# initialize tuple
test_tup = (10, 4, 5, 6, 7, 6, 8, 3, 4)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# initialize N
N = 3
 
# Chunk Tuples to N using numpy
res = np.array_split(test_tup, len(test_tup)/N)
 
# printing result
print("The tuples after chunking are : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output:

The original tuple : (10, 4, 5, 6, 7, 6, 8, 3, 4)
The tuples after chunking are : [array([10,  4,  5]), array([6, 7, 6]), array([8, 3, 4])]
 

Time complexity: O(n) where n is the size of the tuple. 
Auxiliary Space: O(n)

Method #4: Using itertools.islice():

Python3




import itertools
def chunk(iterable, size):
    it = iter(iterable)
    return iter(lambda: tuple(itertools.islice(it, size)), ())
test_tup = (10, 4, 5, 6, 7, 6, 8, 3, 4)
# printing original tuple
print("The original tuple : " + str(test_tup))
N = 3
res = [x for x in chunk(test_tup, N)]
print("The tuples after chunking are : " + str(res))
#This code is contributed by Jyothi pinjala.


Output

The original tuple : (10, 4, 5, 6, 7, 6, 8, 3, 4)
The tuples after chunking are : [(10, 4, 5), (6, 7, 6), (8, 3, 4)]

Time complexity: O(n)  
Auxiliary Space: O(n)

Method #6: Using recursion

You can also chunk an iterable using recursion. This approach may not be as efficient as some of the other methods, but it can be a good exercise in recursion.

 step-by-step approach:

  1. Define a function called “chunk” that takes two arguments: an iterable and a chunk size.
  2. If the length of the iterable is less than or equal to the chunk size, return a list containing the iterable.
  3. Otherwise, use recursion to split the iterable into chunks of size “size”.
  4. Append the first chunk to a list called “chunks”.
  5. Return the “chunks” list.

Python3




def chunk(iterable, size):
    if len(iterable) <= size:
        return [iterable]
    else:
        chunks = chunk(iterable[size:], size)
        chunks.insert(0, iterable[:size])
        return chunks
 
test_tup = (10, 4, 5, 6, 7, 6, 8, 3, 4)
# printing original tuple
print("The original tuple : " + str(test_tup))
N = 3
res = chunk(test_tup, N)
print("The tuples after chunking are : " + str(res))


Output

The original tuple : (10, 4, 5, 6, 7, 6, 8, 3, 4)
The tuples after chunking are : [(10, 4, 5), (6, 7, 6), (8, 3, 4)]

Time complexity: O(n log(n)), where n is the length of the iterable .
Auxiliary space: O(n log(n)), where n is the length of the iterable .

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments