How to Make my Merge output Horizontally instead of Vertically in python

Question:

I have this python3 code that merges my sub-list to a single list:

l=[[4, 5, 6], [10], [1, 2, 3], [10], [1, 2, 3], [10], [4, 5, 6], [1, 2, 3], [4, 5, 6], [4, 5, 6], [7, 8, 9], [1, 2, 3], [7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9], [4, 5, 6], [10], [7, 8, 9], [7, 8, 9]]

import itertools
merged = list(itertools.chain(*l))

from collections import Iterable

def flatten(items):
    """Yield items from any nested iterable; see Reference."""
    for x in items:
        if isinstance(x, Iterable) and not 
isinstance(x, (str, bytes)):
            for sub_x in flatten(x):
                yield sub_x
        else:
            yield x

merged = list(itertools.chain(*l))
merged

The Undesired Shape of the Output

Though the output produces what I want but the shape of the output is not what I want
the output comes out in vertical shape as shown bellow:

[4,
5,
6,
10,
1,
2,
3,
10,
1,
2,
3,
10,
4,
5,
6,
1,
2,
3,
4,
5,
6,
4,
5,
6,
7,
8,
9,
1,
2,
3,
7,
8,
9,
1,
2,
3,
4,
5,
6,
7,
8,
9,
4,
5,
6,
10,
7,
8,
9,
7,
8,
9]

The Desirable Shape of the Output as I Would Want It

I would rather want the output to come out horizontally as I present bellow:

[4, 5, 6, 10, 1, 2, 3, 10, 1, 2, 3, 10, 4, 5, 6, 1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9, 1, 2, 3, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 4, 5, 6, 10, 7, 8, 9, 7, 8, 9]

Please help me out, I will not mind if there is a way to make this happen different from my code.

Asked By: Daniel James

||

Answers:

You can do it like this:

In [5]: for x in merged:
   ...:     print(x, end=' ')
   ...:     
4 5 6 10 1 2 3 10 1 2 3 10 4 5 6 1 2 3 4 5 6 4 5 6 7 8 9 1 2 3 7 8 9 1 2 3 4 5 6 7 8 9 4 5 6 10 7 8 9 7 8 9
Answered By: Mayank Porwal

Instead just use list comprehention:

l=[[4, 5, 6], [10], [1, 2, 3], [10], [1, 2, 3], [10], [4, 5, 6], [1, 2, 3], [4, 5, 6], [4, 5, 6], [7, 8, 9], [1, 2, 3], [7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9], [4, 5, 6], [10], [7, 8, 9], [7, 8, 9]]

new_l=[j for i in l for j in i]
print(new_l)

Output :

C:UsersDesktop>py x.py
[4, 5, 6, 10, 1, 2, 3, 10, 1, 2, 3, 10, 4, 5, 6, 1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9, 1, 2, 3, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 4, 5, 6, 10, 7, 8, 9, 7, 8, 9]
Answered By: Rarblack
from collections import Counter
import itertools
import operator

list1=[[4, 5, 6], [10], [1, 2, 3], [10], [1, 2, 3], [10], [4, 5, 6], [1, 2, 3], [4, 5, 6], [4, 5, 6], [7, 8, 9], [1, 2, 3], [7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9], [4, 5, 6], [10], [7, 8, 9], [7, 8, 9]]

dd = [item for sublist in list1 for item in sublist]
print(dd) # method 1

out1 = reduce(operator.concat,list1)
print(out1) # method 2

merged1 = list(itertools.chain.from_iterable(list1))
print(merged1) # method 3

merged2 = list(itertools.chain(*list1))
print(merged2) # method 4
Answered By: Soudipta Dutta