-2

I have a list of tuples:

listoftuples = [(('elementone', 'elementtwo'), 'elementthree')(....

Now I want to output this list as:

listoftuples = [('elementone', 'elementtwo', 'elementthree')(....

How can i remove those extra parantheses? I have tried to strip them put that doesn't work.

Joep Groentesoep
  • 165
  • 2
  • 10

1 Answers1

1

If the depth is 2, then you can use itertools:

import itertools
listoftuples = [(('elementone', 'elementtwo'), 'elementthree')]
final_list = [tuple(itertools.chain.from_iterable([i] if not isinstance(i, tuple) else i for i in b)) for b in listoftuples]

Output:

[('elementone', 'elementtwo', 'elementthree')]

However, with arbitrary depth, it is best to use recursion:

def flatten(s):
   if not isinstance(s, tuple):
      yield s
   else:
      for b in s:
          for i in flatten(b):
              yield i


listoftuples = [(('elementone', 'elementtwo'), 'elementthree')]
final_list = map(tuple, map(flatten, listoftuples))

Output:

[('elementone', 'elementtwo', 'elementthree')]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102