-1

How would you code for the following outcome?

tuple_list = [('a', 1), ('b', 3), ('c', 2), ...]
def flatten_tuple(tuple_list):
    magic_happens here
    return flat_list
flat_list = ['a', 1, 'b', 3, 'c', 2, ...]

It's a simple problem to solve this way:

def flatten_tuple(tuple_list):
    flat_list = []
    for a, b in tuple_list:
        flat_list.append(a)
        flat_list.append(b)
    return flat_list

Am I missing something which can flatten the tuple list without iterating over the list itself?

Cole
  • 2,489
  • 1
  • 29
  • 48

2 Answers2

2

Use itertools.chain:

from itertools import chain

tuple_list = [('a', 1), ('b', 3), ('c', 2)]

list(chain.from_iterable(tuple_list))
Out[5]: ['a', 1, 'b', 3, 'c', 2]

Or a nested list comprehension:

[elem for sub in tuple_list for elem in sub]
Out[6]: ['a', 1, 'b', 3, 'c', 2]
roippi
  • 25,533
  • 4
  • 48
  • 73
1

You can flatten it using list comprehension like this

tuple_list = [('a', 1), ('b', 3), ('c', 2)]
def flatten_tuple(tuple_list):
    #Method 1
    #import itertools
    #return [item for item in itertools.chain.from_iterable(tuple_list)]

    #Method 2
    return [item for tempList in tuple_list for item in tempList]

print flatten_tuple(tuple_list)

Or from this excellent answer https://stackoverflow.com/a/952952/1903116 (Note works Only in Python 2)

tuple_list = [('a', 1), ('b', 3), ('c', 2)]
def flatten_tuple(tuple_list):
    return list(reduce(lambda x,y: x + y, tuple_list))

print flatten_tuple(tuple_list)
Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • 1
    Might want to add that the last solution works only in Python 2.x. –  Nov 09 '13 at 18:56