
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Split tuple into groups of n in Python
When it is required to split the tuple into 'n' groups, the list comprehension can be used. A tuple is an immutable data type. It means, values once defined can't be changed by accessing their index elements. If we try to change the elements, it results in an error. They are important contains since they ensure read-only access.
The list comprehension is a shorthand to iterate through the list and perform operations on it.
Below is a demonstration for the same −
Example
my_tuple = (12, 34, 32, 41, 56, 78, 9, 0, 87, 53, 12, 45, 12, 6) print ("The tuple is : ") print(my_tuple) my_result = tuple(my_tuple[x:x + 3] for x in range(0, len(my_tuple), 3)) print ("The resultant tuple is : ") print(my_result)
Output
The tuple is : (12, 34, 32, 41, 56, 78, 9, 0, 87, 53, 12, 45, 12, 6) The resultant tuple is : ((12, 34, 32), (41, 56, 78), (9, 0, 87), (53, 12, 45), (12, 6))
Explanation
- A tuple is defined, and is displayed on the console.
- It is iterated over, and grouped in terms of 3 elements in a tuple.
- It is done using list comprehension.
- This operation's data is stored in a variable.
- This variable is the output that is displayed on the console.
- Related Articles
- Split string into groups - JavaScript
- Python - Split list into all possible tuple pairs
- Split Array of items into N Arrays in JavaScript
- How to a split a continuous variable into multiple groups in R?
- Split String of Size N in Python
- Split number into n length array - JavaScript
- Python program to convert Set into Tuple and Tuple into Set
- Convert a list into tuple of lists in Python
- Conversion to N*N tuple matrix in Python
- How can I append a tuple into another tuple in Python?
- How to split a vector into smaller vectors of consecutive values in R?\n
- How to randomly split a vector into n vectors of different lengths in R?
- How to split Python tuples into sub-tuples?
- Python – Split Numeric String into K digit integers
- Program to group a set of points into k different groups in Python

Advertisements