Split tuple into groups of n in Python

PythonServer Side ProgrammingProgramming

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

Live Demo

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.
raja
Published on 13-Mar-2021 05:39:36
Advertisements