python range() with duplicates?

Issue

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

You can do:

>>> [i for i in range(5) for _ in range(3)]
[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]

the range(3) part should be replaced with your number of repetitions…

BTW, you should use generators


Just to make it clearer, the _ is a variable name for something you don’t care about (any name is allowed).

This list comprehension uses nested for loops and are just like that:

for i in range(5):
    for j in range(3):
        #your code here

Answered By – JBernardo

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.