Q:

Python program to chunk tuples to N size

belongs to collection: Python Tuple Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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)]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to access front and rear element fr... >>
<< Python program to check if the tuple has any none ...