1

I have the following list structure:

the_given_list = [[[1],[2],[3]],[[1],[2],[3]]]

Indeed len(the_given_list) returns 2. I need to make the following list:

the_given_list = [[1,2,3],[1,2,3]]

How to do it?

PersianGulf
  • 2,845
  • 6
  • 47
  • 67
  • Possible duplicate of [How to make a flat list out of list of lists](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists) – R4444 Aug 06 '19 at 05:42

5 Answers5

4
[sum(x, []) for x in the_given_list]

Flatten the first-order element in the_given_list.

the_given_list = [sum(x, []) for x in the_given_list]
print(the_given_list)
ComplicatedPhenomenon
  • 4,055
  • 2
  • 18
  • 45
1

To explain the above answer https://stackoverflow.com/a/57369395/1465553, this list

[[[1],[2],[3]],[[1],[2],[3]]]

can be seen as

[list1, list2]

and,

>> sum([[1],[2],[3]], [])
[1,2,3]
>>> sum([[1],[2],[3]], [5])
[5, 1, 2, 3]

Since the second argument to method sum defaults to 0, we need to explicitly pass empty list [] to it to overcome type mismatch (between int and list).

https://thepythonguru.com/python-builtin-functions/sum/

Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79
1

Use itertools.chain

In [15]: from itertools import chain                                                                                                                                                                        

In [16]: [list(chain(*i)) for i in the_given_list]                                                                                                                                                          
Out[16]: [[1, 2, 3], [1, 2, 3]]
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
0
the_given_list  = [ [ s[0] for s in f ] for f in the_given_list ]
0

Another solution:

the_given_list = [[[1],[2],[3]],[[1],[2],[3]]]
print([[j for sub in i for j in sub] for i in the_given_list])

Gives me:

[[1, 2, 3], [1, 2, 3]]

Check the original answer on list flattening:

https://stackoverflow.com/a/952952/5501407

R4444
  • 2,016
  • 2
  • 19
  • 30