Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a list of integers with duplicate values in Python

This question will no doubt to a piece of cake for a Python 2.7 expert (or enthusiast), so here it is.

How can I create a list of integers whose value is duplicated next to it's original value like this?

a = list([0, 0, 1, 1, 2, 2, 3, 3, 4, 4])

It's really easy to do it like this:

for i in range(10): a.append(int(i / 2))

But i'd rather have it in one simple line starting a = desired output.

Thank you for taking the time to answer.

PS. none of the "Questions that may already have your answer were what I was looking for.

like image 523
cookertron Avatar asked Jul 31 '15 10:07

cookertron


2 Answers

>>> [i//2 for i in xrange(10)]
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]

A simple generic approach:

>>> f = lambda rep, src: reduce(lambda l, e: l+rep*[e], src, [])
>>> f(2, xrange(5))
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]
>>> f(3, ['a', 'b'])
['a', 'a', 'a', 'b', 'b', 'b']
like image 174
Vlad Avatar answered Oct 27 '22 22:10

Vlad


>>> sorted(2*range(5))
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]
like image 33
a_guest Avatar answered Oct 27 '22 22:10

a_guest