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?
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.
array_split(list, n) will simply split the list into n parts.
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? 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.
>>> l = [1,2,3,4]
>>> [it for it in l for _ in range(2)]
[1, 1, 2, 2, 3, 3, 4, 4]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With