kentwait - 2 months ago 5

Python Question

Is there a Python builtin that repeats each element of a list based on the corresponding value in another list? For example

`A`

`x`

`2`

`y`

`>>> x = ['A', 'B', 'C']`

>>> y = [2, 1, 3]

>>> f(x, y)

['A', 'A', 'B', 'C', 'C', 'C']

Or to put it another way, what is the fastest way to achieve this operation?

Answer

One way would be the following

```
x = ['A', 'B', 'C']
y = [2, 1, 3]
s = []
for a, b in zip(x, y):
s.extend([a] * b)
print(s)
```

result

```
['A', 'A', 'B', 'C', 'C', 'C']
```

Source (Stackoverflow)

Comments