+ 8

Flatten the list in one line (challenge)

Here's a little challenge: Convert this: list = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] to this: [1, 2, 3, 4, 5, 6, 7, 8, 9] with one line of code. (not counting the first line, which is list = [[1, 2, 3], [4, 5, 6], [7], [8, 9]])

10th Aug 2017, 7:35 PM
David Ashton
David Ashton - avatar
14 Answers
10th Aug 2017, 7:53 PM
VcC
VcC - avatar
+ 4
VcC has the one I was thinking of but Tim's works fine too!
10th Aug 2017, 10:52 PM
David Ashton
David Ashton - avatar
+ 4
print([element for sublist in list for element in sublist]) is shorthand for newlist = [] for sublist in list: for element in sublist: newlist.append(element) print(newlist) https://code.sololearn.com/c8AzvmAQv5yc/#py
11th Aug 2017, 7:43 AM
David Ashton
David Ashton - avatar
+ 4
Another way is simply: print(sum(list, []) but this is apparently slower.
11th Aug 2017, 4:41 PM
David Ashton
David Ashton - avatar
+ 4
@VcC your cool code suggests that it is not slower. I got that idea from https://mathieularose.com/how-not-to-flatten-a-list-of-lists-in-JUMP_LINK__&&__python__&&__JUMP_LINK/
11th Aug 2017, 8:41 PM
David Ashton
David Ashton - avatar
10th Aug 2017, 8:21 PM
Tim Thuma
Tim Thuma - avatar
+ 3
@Eric sum() is just a built-in function that adds the elements of an iterable. E.g. this_list = [1, 2, 3, 4] print(sum(this_list)) # outputs 10 sum(list, []) adds (concatenates) the lists in 'list' so in the challenge example, print(sum(sum(Iist, []))) yields 45
11th Aug 2017, 8:40 PM
David Ashton
David Ashton - avatar
+ 2
@VcC kindly explain your code for me
11th Aug 2017, 6:11 AM
Otumian Empire
Otumian Empire - avatar
13th Aug 2017, 11:28 PM
MichaƂ Bujakowski
MichaƂ Bujakowski - avatar
0
You take each element from each sib list of the main list, and make a list out of this !
11th Aug 2017, 6:18 AM
VcC
VcC - avatar
0
Why isit slower?
11th Aug 2017, 5:07 PM
VcC
VcC - avatar
0
Don't see such a big difference, see here. In fact the sum version looks faster https://code.sololearn.com/cHxS7O7vr4nD/?ref=app
11th Aug 2017, 5:29 PM
VcC
VcC - avatar
0
The difference is 100% to 200% ( with an improved version of chrono which deducts the duration of the call to an empty function) - so the sum version is indeed slower... What is funny is that the multiple line naive version with a for loop is much faster ! Interesting article.
12th Aug 2017, 7:23 AM
VcC
VcC - avatar