Skip to content Skip to sidebar Skip to footer

Flatten Nested Tuples

I have a list of tuples, some of which are nested: [(name,(6,9.0,2.4),link),(name,(7.8,9.0,5),link)...] I would like to un-nest the inner tuple for each item in the list, but pres

Solution 1:

Given

lst = [('xyz',(6,9.0,2.4),'link1'),('abc',(7.8,9.0,5),'link2')]

Iterate over lst and unpack the inner tuples into the outer tuples. You can do this with a list comprehension.

>>> [(x, *y, z) for x, y, z in lst]
[('xyz', 6, 9.0, 2.4, 'link1'), ('abc', 7.8, 9.0, 5, 'link2')]

Works on python3.6. For older versions, use tuple concatenation:

>>> [(x,) + y + (z,) for x, y, z in lst]
[('xyz', 6, 9.0, 2.4, 'link1'), ('abc', 7.8, 9.0, 5, 'link2')]

Post a Comment for "Flatten Nested Tuples"