Given your particular use case Jean's answer would be better. But if you want to make that nested tuple into a single dimensional tuple, the more canonical operation is called flatten()
. flatten()
takes an arbitrarily-nested sequence and 'flattens' it into sequence with no nesting. flatten()
isn't included in the python standard libraries, but is an incredibly useful operation included in many other languages. I took this below implementation from here, which includes other implementations and discusses their strengths and weaknesses.
def flatten(l, ltypes=(list, tuple)):
ltype = type(l)
l = list(l)
i = 0
while i < len(l):
while isinstance(l[i], ltypes):
if not l[i]:
l.pop(i)
i -= 1
break
else:
l[i:i + 1] = l[i]
i += 1
return ltype(l)
The usage is simple:
a = ((1, 2), (3,), (4, (5, 6)))
flatten(a) # -> (1, 2, 3, 4, 5, 6)
a = hi(6) # -> (0, (0, (0, (0, (0, (0, 1))))))
flatten(a) # -> (0, 0, 0, 0, 0, 0, 1)