Repeating elements of a list n times
In case you really want result as list, and generator is not sufficient:
import itertools
lst = range(1,5)
list(itertools.chain.from_iterable(itertools.repeat(x, 3) for x in lst))
Out[8]: [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
Create list of single item repeated N times
You can also write:
[e] * n
You should note that if e is for example an empty list you get a list with n references to the same list, not n independent empty lists.
Performance testing
At first glance it seems that repeat is the fastest way to create a list with n identical elements:
>>> timeit.timeit('itertools.repeat(0, 10)', 'import itertools', number = 1000000)
0.37095273281943264
>>> timeit.timeit('[0] * 10', 'import itertools', number = 1000000)
0.5577236771712819
But wait - it's not a fair test...
>>> itertools.repeat(0, 10)
repeat(0, 10) # Not a list!!!
The function itertools.repeat
doesn't actually create the list, it just creates an object that can be used to create a list if you wish! Let's try that again, but converting to a list:
>>> timeit.timeit('list(itertools.repeat(0, 10))', 'import itertools', number = 1000000)
1.7508119747063233
So if you want a list, use [e] * n
. If you want to generate the elements lazily, use repeat
.
Creating a list of mutable items repeated N times
I just figured out I can do this through:
from copy import deepcopy
a = [[1],[2],[3]]
n = 3
b = [deepcopy(val) for _ in range(n) for val in a]
Now if I set b[0][0] = 0
, I will get b == [[0],[2],[3],[1],[2],[3],[1],[2],[3]]
.
Creating a list repeated n times using an existing variable which is mutable
You can just use .copy()
:
import numpy as np
R = np.array([[2,3,0], [6,78,8],[1,2,3]])
U = [R.copy() for _ in range(3)]
U[1][2,2] = 0
print(U)
Gives:
[array([[ 2, 3, 0],
[ 6, 78, 8],
[ 1, 2, 3]]),
array([[ 2, 3, 0],
[ 6, 78, 8],
[ 1, 2, 0]]),
array([[ 2, 3, 0],
[ 6, 78, 8],
[ 1, 2, 3]])]
Repeat same element n times in a list
You can use replicate
with simplify = FALSE
:
e <- 1:5
n <- 5
list_new <- replicate(n, e, simplify = FALSE)
list_new
#[[1]]
#[1] 1 2 3 4 5
#[[2]]
#[1] 1 2 3 4 5
#[[3]]
#[1] 1 2 3 4 5
#[[4]]
#[1] 1 2 3 4 5
#[[5]]
#[1] 1 2 3 4 5
This is the same output as list(e, e, e, e, e)
.
purrr
also has rerun
function which gives the similar behaviour.
list_new <- purrr::rerun(n, e)
Creating a list of N numbers from existing list each repeated K times
Thanks, everyone for the answers.
It seems there is an easier and more direct way to solve this using Numpy.
np.repeat(x, 3).tolist()
prints exactly what I needed:
[6, 6, 6, 7, 7, 7, 8, 8, 8]
Repeat a list within a list X number of times
No need for any functions:
>>> L = [1,2,3,4,5]
>>> [L]*3
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
However, you should note that if you change one value in any of the lists, all the others will change because they reference the same object.
>>> mylist = [L]*3
>>> mylist[0][0] = 6
>>> print mylist
[[6, 2, 3, 4, 5], [6, 2, 3, 4, 5], [6, 2, 3, 4, 5]]
>>> print L
[6, 2, 3, 4, 5]
To avoid this:
>>> L = [1,2,3,4,5]
>>> mylist = [L[:] for _ in range(3)]
>>> mylist[0][0] = 6
>>> print L
[1, 2, 3, 4, 5]
>>> print mylist
[[6, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
Notice how L
didn't change, and only the first list in mylist
changed.
Thanks everyone in the comments for helping :).
Related Topics
Django Csrf Check Failing With an Ajax Post Request
Filter Dataframe Rows If Value in Column Is in a Set List of Values
Read Subprocess Stdout Line by Line
Extract File Name from Path, No Matter What the Os/Path Format
How Does Tuple Comparison Work in Python
Why Is "1000000000000000 in Range(1000000000000001)" So Fast in Python 3
Find If 24 Hrs Have Passed Between Datetimes
How to Resize an Image Using Pil and Maintain Its Aspect Ratio
How to Make One Python File Run Another
How to Update a Plot in Matplotlib
How to Merge Dictionaries of Dictionaries
How to Fix: "Unicodedecodeerror: 'Ascii' Codec Can't Decode Byte"
Convert Python Dict into a Dataframe
How to Read CSV Data into a Record Array in Numpy