I am basically trying to get my head around using a list comprehension with this basic bit of code. Im trying to duplicate a list item by the value of the list item:
y = [1, 2, 0, 1]
x = []
for i in y:
for j in range(i):
x.append(i)
# Desired output
>>> [1, 2, 2, 1]
x = [i for _ in range(i) for i in y]
# Wrong output
>>> [1, 2, 0, 1]
# Right output
x = [j for j in y for _ in range(j)]
>>> [1, 2, 2, 1]
I just cant seem to get my head around why I get the wrong output for the second example. Could someone explain what is wrong here. Thanks.