how to duplicate array entries
Gary Herron
gherron at islandtraining.com
Mon Jan 11 02:20:52 EST 2010
Paul Rudin wrote:
> Sebastian <sebastian.langer at gmx.de> writes:
>
>
>> Hi there,
>>
>> I have an array x=[1,2,3]
>>
>
> In python such an object is called a "list".
>
> (In cpython it's implemented as an automatically resizable array.)
>
>
>> Is there an operator which I can use to get the result
>> [1,1,1,2,2,2,3,3,3] ?
>>
>
> There's no operator that will give you that directly - but there are
> plenty of one-liners that will yield that list.
> e.g:
>
>
>>>> list(itertools.chain(*([x]*3 for x in [1,2,3])))
>>>>
> [1, 1, 1, 2, 2, 2, 3, 3, 3]
>
List comprehension also works nicely for this problem, and may be
clearer to some.
>>> x = [1,2,3]
>>> print [i for i in x for k in range(3)]
[1, 1, 1, 2, 2, 2, 3, 3, 3]
Gary Herron
More information about the Python-list
mailing list