Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python range() with duplicates?

Tags:

python

list

range

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
like image 968
wim Avatar asked Aug 25 '11 05:08

wim


1 Answers

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
like image 144
JBernardo Avatar answered Nov 02 '22 05:11

JBernardo