- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Chunk Tuples to N in Python
When it is required to chunk the tuples to 'N' values, list comprehension is used.
The list comprehension is a shorthand to iterate through the list and perform operations on it.
Below is a demonstration of the same −
Example
my_tuple_1 = (87, 90, 31, 85,34, 56, 12, 5) print("The first tuple is :") print(my_tuple_1) N = 2 print("The value of 'N' has been initialized") my_result = [my_tuple_1[i : i + N] for i in range(0, len(my_tuple_1), N)] print("The tuple after chunking is : ") print(my_result)
Output
The first tuple is : (87, 90, 31, 85, 34, 56, 12, 5) The value of 'N' has been initialized The tuple after chunking is : [(87, 90), (31, 85), (34, 56), (12, 5)]
Explanation
- A tuple is defined, and is displayed on the console.
- The value of 'N' is initialized.
- The tuple is iterated over, using the 'range' method, and is divided into chunks using the '[]' brackets, i.e indexing.
- It is then converted to a list type.
- This result is assigned to a value.
- It is displayed as output on the console.
Advertisements