'python range() with duplicates?

Everybody knows that a list of numbers can be obtained with range like this;:

>>> list(range(5))
[0, 1, 2, 3, 4]

If you want, say, 3 copies of each number you could use:

>>> list(range(5)) * 3
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4]

But is there an easy way using range to repeat copies like this instead?

[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]

Examples:

sorted(list(range(5)) * 3)   # has unnecessary n * log(n) complexity
[x//3 for x in range(3*5)]   # O(n), but division seems unnecessarily complicated


Solution 1:[1]

Try this:

itertools.chain.from_iterable(itertools.repeat(x, 3) for x in range(5))

Solution 2:[2]

from itertools import chain, izip
list(chain(*izip(*[xrange(5)]*3)))

Gives

[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]

Leave off the list and you have a generator.

EDIT: or even better (leaves out a function call to izip):

list(chain(*([x]*3 for x in xrange(5))))

Solution 3:[3]

There is a very simple way to do this with a help from numpy. Example:

>>> import numpy as np
>>> np.arange(5*3) // 3
array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4])

With range you can do the following:

>>> list(map(lambda x: x // 3, range(5*3)))
[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]

Remembering that // performs a strict integer division.

Solution 4:[4]

>>> from itertools import chain, izip, tee
>>> list(chain.from_iterable(izip(*tee(range(5), 3))))
[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]

Solution 5:[5]

A cool iterator using another approach:

>>> from collections import Counter
>>> Counter(range(5) * 3).elements()

Solution 6:[6]

I like to Keep It Simple :)

>>> sorted(list(range(5)) * 3)
[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]

Solution 7:[7]

import itertools
[x for tupl in itertools.izip(*itertools.tee(range(0,5),3)) for x in tupl]

Or:

[x for tupl in zip(range(0,5), range(0,5), range(0,5)) for x in tupl]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michael J. Barber
Solution 2
Solution 3 Matheus Araujo
Solution 4 pillmuncher
Solution 5
Solution 6 pawroman
Solution 7 KZ.