Chunk Tuples to N in Python

PythonServer Side ProgrammingProgramming

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

Live Demo

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.
raja
Published on 11-Mar-2021 09:56:27
Advertisements