- 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
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
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 −
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)
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))
- 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
- Python - Split list into all possible tuple pairs
- How to a split a continuous variable into multiple groups in R?
- Split String of Size N in Python
- 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