Caerus
Caerus

Reputation: 674

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 preserve the outer tuple:

[(name,6,9.0,2.4,link),(name,7.8,9.0,5,link)...]

This is different from the solution to the question posed here in which the solution sought to preserve the pairs.

Upvotes: 3

Views: 760

Answers (1)

cs95
cs95

Reputation: 402583

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')]

Upvotes: 4

Related Questions