Creating a list from different sublists repeated a different number of times

Viewed 66

Please could I have help with the following query in Python 3.9. I have the following sublists:

[0, 1]
[1, 3]
[2, 5]

I would like to make a new list with each of these sublists repeated a different number of times. Required output:

[[0,1],[0,1],[0,1],[1,3],[1,3],[2,5],[2,5],[2,5],[2,5]]

I have tried doing the following:

[[[0,1]]*3,[[1,3]]*2,[[2,5]]*4]

However I get this:

[[[0,1],[0,1],[0,1]],[[1,3],[1,3]],[[2,5],[2,5],[2,5],[2,5]]]

How do I get my desired output? Or alternatively, how do I just flatten it by one level? Thank you

2 Answers

You can just unpack the sublists:

[*[[0,1]]*3, *[[1,3]]*2, *[[2,5]]*4]
# [[0, 1], [0, 1], [0, 1], [1, 3], [1, 3], [2, 5], [2, 5], [2, 5], [2, 5]]

Note however, that the resulting sublists are not independent, but references to the same list objects (changes made to one sublist will be reflected in all the equal others)! Better use generators/comprehensions:

[*([0,1] for _ in range(3)), 
 *([1,3] for _ in range(2)), 
 *([2,5] for _ in range(4))]
# [[0, 1], [0, 1], [0, 1], [1, 3], [1, 3], [2, 5], [2, 5], [2, 5], [2, 5]]

The more general question of 1-level flattening has been asked and answered multiple times, but the main options are the nested comprehension:

[x for sub in lst for x in sub]

or itertools.chain:

[*chain(lst)]

You can use list loop:

r1 = [0, 1]
r2 = [1, 3]
r3 = [2, 5]
h = [*(r1 for x in range(3)),
     *(r2 for x in range(2)),
     *(r3 for x in range(4))]
print(h)
Related