How do I create a list of following numbers, based on list1?
list1=[2,1,3]
For example:
list1=[2,1,3]
I want to print:
[1, 1, 2, 3, 3, 3]
(2) (1) (3) #<-- Ignore this part, I just put it to give you more detail of my question
Above, I want to print two (1's), one(2) and three(3's) because list1 = [2,1,3]
Is there any efficient way I can do this in python3? (- Sorry I'm new to Stack Overflow, so please excuse my lack of effective questioning)
Here is one way of doing this:
list1=[2,1,3]
list2 = []
for j, num in enumerate(list1, 1):
for _ in range(num):
list2.append(j)
print(list2)
Output:
[1, 1, 2, 3, 3, 3]
You can use enumerate()
:
n = [2, 1, 3]
result = []
for i, j in enumerate(n, start=1):
result.extend([i] * j)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With