Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smallest way to expand a list by n

Tags:

python

list

i want to expand a list

[1,2,3,4]

by n

e.g. for n = 2:

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

I'm searching for the smallest possible way to achieve this without any additional librarys. Its easy to do a loop and append each item n times to a new list... but is there a other way?

like image 672
Schinken Avatar asked Apr 08 '12 11:04

Schinken


People also ask

How do I make a list size n?

To create a list of n placeholder elements, multiply the list of a single placeholder element with n . For example, use [None] * 5 to create a list [None, None, None, None, None] with five elements None . You can then overwrite some elements with index assignments.

How do you split a list into N parts?

array_split(list, n) will simply split the list into n parts.

Can you do the len of a list?

There is a built-in function called len() for getting the total number of items in a list, tuple, arrays, dictionary, etc. The len() method takes an argument where you may provide a list and it returns the length of the given list.

How do I reduce the size of a list in Python?

How do I reduce the size of a list in Python? Python offers a function called reduce() that allows you to reduce a list in a more concise way. The reduce() function applies the fn function of two arguments cumulatively to the items of the list, from left to right, to reduce the list into a single value.


1 Answers

>>> l = [1,2,3,4]
>>> [it for it in l for _ in range(2)]
[1, 1, 2, 2, 3, 3, 4, 4]
like image 65
hamstergene Avatar answered Oct 16 '22 11:10

hamstergene