1

I have a tuple of tuples. Each tuple within the tuple can be itself a tuple of tuple with no particular limitation in the nesting.

I would like to flatten this into a single tuple containing all the elements in the same order than a print would print them on screen.

For example:

a = ( 1 , (2, 3), (4, (5), (6, 7, (8, 9))))

would become:

( 1 , 2, 3, 4, 5, 6, 7, 8, 9 )

I may be wrong but I have not seen the same question. I am quite new to Python so I do not know if there is a Python way to do this (I would have gone for a generator personally).

BlueTrin
  • 9,610
  • 12
  • 49
  • 78

2 Answers2

2

You can use a recusive flattening function:

def flatten(seq):
  for x in seq:
    if isinstance(x, basestring):  # use isinstance(x, str) in python3
       yield x
       continue
    try:
      # in python >=3.3, can use the nifty "yield from", like: yield from flatten(x)
      for y in flatten(x):
        yield y
    except TypeError:
       yield x  # not iterable

print tuple(flatten(a))
=> (1, 2, 3, 4, 5, 6, 7, 8, 9)

Please note that in your initialisation of a, (5) is equivalent to 5. What you probably meant is a tuple of size 1, which is created using a comma, like: (5,).

shx2
  • 61,779
  • 13
  • 130
  • 153
  • This doesn't work for strings. –  Jan 04 '14 at 17:22
  • @delnan: in fact I gave a bad example, I have strings in my tuple. It seems to complain about the number of recursions because the strings are fairly long and I suspect it is trying to create the iterator letter by letter – BlueTrin Jan 04 '14 at 17:29
  • I vote to close my question. someone found a duplicate ? – BlueTrin Jan 04 '14 at 17:31
  • 2
    @BlueTrin Worse, it recurses infinitely if any (non-empty) string is encountered: Iterating a string yields one-character strings, and iterating those again yields one-character strings (one, to be precise), and so on without end. –  Jan 04 '14 at 17:32
1

You can use this recursive function:

a = ( 1 , (2, 3), (4, (5), (6, 7, (8, 9))))
b = []
def tup(x):
    if not(type(x) == tuple):
        b.append(x)
    else:
        for i in range(len(x)):
            tup(x[i])

tup(a)
print(b)
RGS
  • 964
  • 2
  • 10
  • 27