consider a list l=[1,2,3,4,5].
if we want to unpack the list and also to print, we use * operator to unpack
l=[1,2,3,4,5]
print(*l,sep="\n")
output:
1
2
3
4
5
It is in case of single simple list.
If I have nested list and want to unpack all the sublists like above☝.
consider a sublist sl=[[1,2,3],[4,5,6],[7,8,9]]
If I put ** in the print satement it throws an error message.
sl=[[1,2,3],[4,5,6],[7,8,9]]
print(**sl,sep="\n")
It doesn't work.
I want the output as
1
2
3
4
5
6
7
8
9
Is there any chance to unpack the sublists of nested list without loops
CodePudding user response:
You can use itertools.chain
like below:
>>> from itertools import chain
>>> sl=[[1,2,3],[4,5,6],[7,8,9]]
>>> print(*(chain.from_iterable(sl)),sep="\n")
1
2
3
4
5
6
7
8
9
CodePudding user response:
You could flatten the list and then unpack it.
l = [[1,2,3],[4,5,6],[7,8,9]]
print(*[elt for sl in l for elt in sl])
CodePudding user response:
To get the output you require you could do this:
sl=[[1,2,3],[4,5,6],[7,8,9]]
print('\n'.join([str(x) for y in sl for x in y]))