

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- Split string into groups - JavaScript
- Python - Split list into all possible tuple pairs
- Split Array of items into N Arrays in JavaScript
- Split number into n length array - JavaScript
- Split String of Size N in Python
- How to a split a continuous variable into multiple groups in R?
- Python program to convert Set into Tuple and Tuple into Set
- Conversion to N*N tuple matrix in Python
- Convert a list into tuple of lists in Python
- Rearranging cards into groups in JavaScript
- 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 can I append a tuple into another tuple in Python?
- Convert a list into a tuple in Python.
- Program to group a set of points into k different groups in Python
Advertisements