-1

I have a list of nested tuples as

[(('p1', 'p2'), ('m1',)), (('p2', 'p1'), ('m1',))]

How can i convert it into list of tuples as

[('p1', 'p2', 'm1'), ('p2', 'p1', 'm1')]

without using for loop

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Nitin
  • 2,572
  • 5
  • 21
  • 28

2 Answers2

4

You can do with itertools.chain,

In [91]: from itertools import chain
In [92]: [tuple(chain(*item)) for item in a]
Out[92]: [('p1', 'p2', 'm1'), ('p2', 'p1', 'm1')]
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
3

You can use list comprehension with a generator as element in the tuple(..) constructor:

[tuple(x for elem in row for x in elem) for row in data]

The code fragment in boldface is a generator: for every row (i.e. (('p1', 'p2'), ('m1',))) it yield the elements that are two levels deep so: p1, p2 and m1. These are converted into a tuple.

Or you can use itertools:

from itertools import chain

[tuple(chain(*row)) for row in data]

This generates:

>>> data = [(('p1', 'p2'), ('m1',)), (('p2', 'p1'), ('m1',))]
>>> [tuple(x for elem in row for x in elem) for row in data]
[('p1', 'p2', 'm1'), ('p2', 'p1', 'm1')]
>>> [tuple(chain(*row)) for row in data]
[('p1', 'p2', 'm1'), ('p2', 'p1', 'm1')]

You can also use itertools.starmap(..) and list(..) to remove the list comprehension:

from itertools import chain, starmap

list(map(tuple,starmap(chain,data)))

Which gives:

>>> list(map(tuple,starmap(chain,data)))
[('p1', 'p2', 'm1'), ('p2', 'p1', 'm1')]

Note that although you do not write a for loop yourself, of course there is still a loop mechanism in place at the list comprehension or map(..) and starmap(..) functions.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555