Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to split Python tuples into sub-tuples?

How to split Python tuples into sub-tuples?                                     


2 Answers
Samual Sam

The most readable way to split Python tuples into sub-tuples is to slice it up yourself. For example,

x = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)
y = (x[:4], x[4:8], x[8:])
print(y)

This will give the output:

((0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11, 12, 13, 14))

You can do this even in loops using list comprehensions. For example, to split it up in chunks of size 3 you can use:

x = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)
y = tuple(x[i : i+4] for i in range(0, len(x), 3))
print(y)

This will give the output:

((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13, 14))
Pythonista

Here is a tuple with 12 integers. In order to split it in four sub-tuple of three elements each, slice a tuple of three successive elements from it and append the segment in a lis. The result will be a list of 4 tuples each with 3 numbers.

>>> tup=(7,6,8,19,2,4,13,1,10,25,11,34)
>>> lst=[]
>>> for i in range(0,10,3):
lst.append((tup[i:i+3]))
>>> lst
[(7, 6, 8), (19, 2, 4), (13, 1, 10), (25, 11, 34)]
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.