0

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

shankar v
  • 1
  • 4
  • just run it in a for loop and append every item into an another list – Ghost Ops Oct 16 '21 at 14:26
  • 1
    Does this answer your question? [How to make a flat list out of a list of lists](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-a-list-of-lists) – nikeros Oct 16 '21 at 14:26
  • @GhostOps Yes we can use for loop to iterate through the each element in the sublist. But I don't want to use loops. Is there any chance to do – shankar v Oct 16 '21 at 14:30

3 Answers3

1

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
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
0

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])
Dev
  • 108
  • 5
0

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]))