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']
Ger
  • 9,076
  • 10
  • 37
  • 48

5 Answers5

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

Fernando Matsumoto
  • 2,697
  • 1
  • 18
  • 24
  • Can you explain the underscore role ? – Ger Oct 18 '15 at 22:37
  • @Ger The underscore is an unused variable. It's used when you want to ignore a value. It can also have [other meanings](http://stackoverflow.com/questions/5893163/what-is-the-purpose-of-the-single-underscore-variable-in-python) in other contexts. – Fernando Matsumoto Oct 18 '15 at 22:40
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.

Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69
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']

sam
  • 2,033
  • 2
  • 10
  • 13
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']
LetzerWille
  • 5,355
  • 4
  • 23
  • 26
  • @RobertMoskal map and itertools are faster than list comprehensions. Less readability, but more performance. – LetzerWille Oct 18 '15 at 22:44
  • 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. – Robert Moskal Oct 18 '15 at 23:16
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']
Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214