Skip to content
Advertisement

Repeat list elements based in another list

I would like to repeat elements from one list based in a second list, like this:

i = 0
j = [1, 4, 10]
z = [11.65, 11.69, 11.71]
for x in j:
    while i <= x:
        print(x)
        i += 1

I’ve got this result:

1
1
4
4
4
10
10
10
10
10
10

I’d like to get this result:

11.65
11.65
11.69
11.69
11.69
11.71
11.71
11.71
11.71
11.71
11.71

Advertisement

Answer

You may iterate on both list together, using zip, then increase i until you reach the bound of the current value

i = 0
j = [1, 4, 10]
z = [11.65, 11.69, 11.71]
for bound, value in zip(j, z):
    while i <= bound:
        print(value)
        i += 1
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement