cookertron
cookertron

Reputation: 198

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.

Upvotes: 7

Views: 2080

Answers (7)

AA A
AA A

Reputation: 448

The other answers cover the specific case asked in the question, but if you want to duplicate the contents of an arbitrary list, you can use the following:

>>> import itertools
>>> l = [1, 'a', 3]
>>> list(itertools.chain.from_iterable(zip(l,l)))
[1, 1, 'a', 'a', 3, 3]

Upvotes: 0

Vlad
Vlad

Reputation: 18633

>>> [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']

Upvotes: 12

PM 2Ring
PM 2Ring

Reputation: 55499

Here's a technique that works on any list, not just int lists, and doesn't rely on the (relatively) expensive sorted() function. It also lets you specify the number of repetitions.

First, a simple version to solve the problem in the OP:

print [u for v in [[i,i] for i in range(5)] for u in v]

output

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

And now the fancy (but slightly more readable) version.

a = list('abcde')
rep = 3
print [item for sublist in [rep * [i] for i in a] for item in sublist]

output

['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'e', 'e', 'e']

Here's an expanded version of the previous example, written using simple for loops rather than as a nested list comprehension.

b = []
for sublist in [rep * [i] for i in a]:
    for item in sublist:
        b.append(item)
print b

Upvotes: 2

Sreekanth Reddy
Sreekanth Reddy

Reputation: 483

>>> sorted(map(str, range(0,5) + range(0,5)))
['0', '0', '1', '1', '2', '2', '3', '3', '4', '4']

Upvotes: 1

Nihal Sharma
Nihal Sharma

Reputation: 2437

[int(i/2 )for i in range(10)] 

or

[i//2 for i in range(10)]

Upvotes: 0

a_guest
a_guest

Reputation: 36309

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

Upvotes: 2

Selva Mathan
Selva Mathan

Reputation: 31

sorted( range(10)  +  range(10) )

Upvotes: 1

Related Questions