Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Chunk Tuples to N in Python
When it is required to chunk tuples into groups of 'N' values, list comprehension provides an efficient solution. This technique divides a tuple into smaller sub-tuples of specified size.
List comprehension is a shorthand to iterate through sequences and perform operations on them in a single line.
Basic Chunking Example
Here's how to chunk a tuple into groups of N elements ?
my_tuple = (87, 90, 31, 85, 34, 56, 12, 5)
print("The original tuple is:")
print(my_tuple)
N = 2
print(f"Chunking into groups of {N}")
result = [my_tuple[i : i + N] for i in range(0, len(my_tuple), N)]
print("The tuple after chunking is:")
print(result)
The original tuple is: (87, 90, 31, 85, 34, 56, 12, 5) Chunking into groups of 2 The tuple after chunking is: [(87, 90), (31, 85), (34, 56), (12, 5)]
Different Chunk Sizes
Let's see how different N values affect the chunking ?
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
# Chunk into groups of 3
chunks_3 = [numbers[i : i + 3] for i in range(0, len(numbers), 3)]
print("Chunks of 3:", chunks_3)
# Chunk into groups of 4
chunks_4 = [numbers[i : i + 4] for i in range(0, len(numbers), 4)]
print("Chunks of 4:", chunks_4)
Chunks of 3: [(1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11)] Chunks of 4: [(1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11)]
Using a Function
Create a reusable function for tuple chunking ?
def chunk_tuple(input_tuple, chunk_size):
"""Divide a tuple into chunks of specified size."""
return [input_tuple[i : i + chunk_size] for i in range(0, len(input_tuple), chunk_size)]
# Example usage
data = (10, 20, 30, 40, 50, 60, 70)
print("Original tuple:", data)
print("Chunks of 2:", chunk_tuple(data, 2))
print("Chunks of 3:", chunk_tuple(data, 3))
Original tuple: (10, 20, 30, 40, 50, 60, 70) Chunks of 2: [(10, 20), (30, 40), (50, 60), (70,)] Chunks of 3: [(10, 20, 30), (40, 50, 60), (70,)]
How It Works
- The
range(0, len(my_tuple), N)generates starting indices: 0, N, 2N, 3N, etc. - For each index
i, we slice the tuple fromitoi + N - List comprehension collects all slices into a new list
- If the tuple length isn't divisible by N, the last chunk will be smaller
Conclusion
Use list comprehension with tuple slicing to efficiently chunk tuples into groups of N elements. This method handles uneven divisions gracefully by creating smaller final chunks when needed.
Advertisements
