Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create duplicates in the list

Tags:

python

list

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)
like image 908
Ekaterina Avatar asked Jan 23 '17 16:01

Ekaterina


People also ask

Can we add duplicate values in list Python?

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.

Can there be duplicates in a list?

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.

How do you create a repeated value list?

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).


2 Answers

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.

like image 79
Moses Koledoye Avatar answered Oct 23 '22 17:10

Moses Koledoye


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.

like image 30
Mike Müller Avatar answered Oct 23 '22 15:10

Mike Müller