2

I wonder if there is a more elegant way to do the following. For example with list comprehension.

Consider a simple list :

l = ["a", "b", "c", "d", "e"]

I want to duplicate each elements n times. Thus I did the following :

n = 3
duplic = list()
for li in l:
    duplic += [li for i in range(n)]

At the end duplic is :

['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'e', 'e', 'e']

5 Answers 5

4

You can use

duplic = [li for li in l for _ in range(n)]

This does the same as your code. It adds each element of l (li for li in l) n times (for _ in range n).

Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain the underscore role ?
@Ger The underscore is an unused variable. It's used when you want to ignore a value. It can also have other meanings in other contexts.
1

You can use:

l = ["a", "b", "c", "d", "e"]
n=3
duplic = [ li  for li in l for i in range(n)]

Everytime in python that you write

duplic = list()
for li in l:
    duplic +=

there is a good chance that it can be done with a list comprehension.

1 Comment

Just the simplest way !
1

Try this:

l = ["a", "b", "c", "d", "e"]
print sorted(l * 3)

Output:

['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'e', 'e', 'e']

3 Comments

This ones actually elegant!
But what if original list goes not in sorted order? So sorted function will mess up everything.
also impractical for huge lists
0
from itertools import chain

n = 4

 >>>list(chain.from_iterable(map(lambda x: [x]*n,l)))

['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'd', 'd', 'd', 'd', 'e', 'e', 'e', 'e']

2 Comments

@RobertMoskal map and itertools are faster than list comprehensions. Less readability, but more performance.
No arguments. If you are used to the idiom it's no big deal. But if you are used to programming imperatively, you have to run to the internet.
0
In [12]: l
Out[12]: ['a', 'b', 'c', 'd', 'e']

In [13]: n
Out[13]: 3

In [14]: sum((n*[item] for item in l), [])
Out[14]: ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'e', 'e', 'e']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.