'Flatten list of tuples containing tuples [duplicate]

I have a list of tuples, with each tuple containing a tuple pair, coordinates.

list1 = [((11, 11), (12, 12)), ((21, 21), (22, 22)), ((31,31), (32,32))] # list of tuple pairs

Using list comprehension I am trying to generate a list without them being paired but still in the same order. I was able to get the result be looping and using .append() but I was trying to avoid this.

new_list = []
for i in list1:
    for x in i:
        new_list.append(x)

print(new_list)

output:

[(11, 11), (12, 12), (21, 21), (22, 22), (31, 31), (32, 32)]

this works and gives me the result I am looking for:

But when I try list comprehension I get the last tuple pair repeated!

new_list = [x for x in i for i in list1]

print(new_list)

output:

[(31, 31), (31, 31), (31, 31), (32, 32), (32, 32), (32, 32)]

I am sure it is a small thing I am doing wrong so would appreciate the help!!



Solution 1:[1]

Python is having inbuilt function itertools.chain.from_iterable() to achieve the same result:

>>> from itertools import chain
>>> my_list = [((11, 11), (12, 12)), ((21, 21), (22, 22)), ((31,31), (32,32))]


>>> list(chain.from_iterable(my_list))  # OR, list(chain(*my_list))
[(11, 11), (12, 12), (21, 21), (22, 22), (31, 31), (32, 32)]

Solution 2:[2]

Use Alex Martelli's method to flatten a list of lists by one level:

>>> [t for tt in list1 for t in tt]
[(11, 11), (12, 12), (21, 21), (22, 22), (31, 31), (32, 32)]

Solution 3:[3]

This should give you the expected output:

flat_list1 = [result_tuple for coupled_tuples in list1 for result_tuple in coupled_tuples]

Like in your question - where you looped over list1 and then each of it's tuple elements, for coupled_tuples in list1 is the outer loop, for result_tuple in coupled_tuples is the inner loop.

You can have as many independent for x in y clauses as you want in a comprehension just by sticking one after the other.

flat_list1 = [
              result_tuple                       # result
              for coupled_tuples in list1        # outer for loop
              for result_tuple in coupled_tuples # inner for loop
             ]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Moinuddin Quadri
Solution 2 dawg
Solution 3 Eyal Golan