Python program to chunk tuples to N size

In this program, we are given a tuple. We need to create a Python program to create chunks of tuples each of size N from the element of the given tuple.
Submitted by Shivang Yadav, on December 23, 2021

Sending data over the network and mostly all data sharing creates data chunks of definite size and then transfer each chuck as a data packet which is then combined to create the data collection to avoid and overcome errors while transferring. Here, we will be creating a Python program to create chunks of tuples of size N.

Before going further with the problem, let's recap some basic topics that will help in understanding the solution.

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.

Example:

tuple = ("python", "includehelp", 43, 54.23)

Chunk tuples to N size

In this article, we will create a Python program to create chunk tuples of size N from the given tuple.

Input:
(4, 2, 7, 6, 1, 12, 54, 76, 87, 99)
N = 2

Output:
(4, 2), (7, 6), (1, 12), (54, 76), (87, 99)

We need to create chunks of size N, for which will iterate the tuple and take each chunk of size N and create a tuple using it.

Method 1:

One method to solve the problem is by using a direct method. In which, we will iterate the tuple and use another count for size N values to be feeding in new chunk tuples.

# Initializing and printing the tuple 
# and chunk size 

myTup =(4, 2, 7, 6, 1, 12, 54, 76, 87, 99)

print("The elements of tuple are " + str(myTup))

N = 2
print("The chunk size(N) is " + str(N))

# Chunking tuples to N
chunkTup = [myTup[i : i + N] for i in range(0, len(myTup), N)]

print("The list of chunk tuples of size N is " + str(chunkTup))

Output:

The elements of tuple are (4, 2, 7, 6, 1, 12, 54, 76, 87, 99)
The chunk size(N) is 2
The list of chunk tuples of size N is [(4, 2), (7, 6), (1, 12), (54, 76), (87, 99)]

Method 2:

Another approach to solving the problem is by using iter() method to create an iterator of size N, which then we converted into tuple using zip() method.

# Initializing and printing the tuple 
# and chunk size

myTup =(4, 2, 7, 6, 1, 12, 54, 76, 87, 99)

print("The elements of tuple are " + str(myTup))

N = 2

print("The chunk size(N) is " + str(N))

# Chunking tuples to N
chunkTup = list(zip(*[iter(myTup)] * N))

print("The list of chunk tuples of size N is " + str(chunkTup))

Output:

The elements of tuple are (4, 2, 7, 6, 1, 12, 54, 76, 87, 99)
The chunk size(N) is 2
The list of chunk tuples of size N is [(4, 2), (7, 6), (1, 12), (54, 76), (87, 99)]

Python Tuple Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.