I have
list = [a, b, c, d]
and
numbers = [2, 4, 3, 1]
I want to get a list of the type of:
new_list = [a, a, b, b, b, b, c, c, c, d]
This is what I have so far:
new_list=[]
for i in numbers:
for x in list:
for i in range(1,i+1):
new_list.append(x)
You can add or remove elements from Python lists. A list can be sorted too. But by default, a list is not sorted. A Python list can also contain duplicates, and it can also contain multiple elements of different data types.
What are duplicates in a list? If an integer or string or any items in a list are repeated more than one time, they are duplicates.
Using the * Operator The * operator can also be used to repeat elements of a list. When we multiply a list with any number using the * operator, it repeats the elements of the given list. Here, we just have to keep in mind that to repeat the elements n times, we will have to multiply the list by (n+1).
Here's one way to do it using zip
, string multiplication and a list comprehension:
lst = ['a', 'b', 'c', 'd']
numbers = [2 , 4, 3, 1]
r = [x for i, j in zip(lst, numbers) for x in i*j]
print(r)
# ['a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd']
Pay attention to the choice of names when using Python. A name like list
renders the builtin list function unusable.
If the items in lst
are not strings you can simply use a nested comprehension on range
, to duplicate the items in the list.
A nested list comprehension works:
L = ['a','b','c','d']
numbers = [2, 4, 3, 1]
>>> [x for x, number in zip(L, numbers) for _ in range(number)]
['a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd']
The "sub-loop" for _ in range(number)
repeats the value number
times.
Here L
can hold any object, not only strings.
Example:
L = [[1, 2, 3],'b','c', 'd']
numbers = [2, 4, 3, 1]
[x for x, number in zip(L, numbers) for _ in range(number)]
[[1, 2, 3], [1, 2, 3], 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd']
but this flattens the sub list:
[x for i, j in zip(L, numbers) for x in i*j]
[1, 2, 3, 1, 2, 3, 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd']
not exactly the desired result.
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