I need to get same raw multiple times like bellow.
A=[2,3,4,5]
B=[[2,3,4,5],[2,3,4,5],[2,3,4,5],[2,3,4,5],...,[2,3,4,5]]
Number of rows can be change. How can I do this problem?
I need to get same raw multiple times like bellow.
A=[2,3,4,5]
B=[[2,3,4,5],[2,3,4,5],[2,3,4,5],[2,3,4,5],...,[2,3,4,5]]
Number of rows can be change. How can I do this problem?
Try this:
B = [[i for i in A] for n in range(5)]
Change the value in the range ()
call to change the number of copies. This doesn't suffer from reference sharing like the other answers.
Or a shorter equivalent:
B = [A[:] for n in range(5)]
This also doesn't suffer from reference sharing because the slice operator creates a deep copy* as well.
* at least in terms of this input
As has been pointed out, just doing list comprehension in the simplest way will only make multiple references to the same old list. To instead ensure we get a new copy of the list, we can do:
A = [2, 3, 4, 5]
B = [list(A) for i in range(10)]
where list(A)
ensures that we get a copy of A
instead of a reference to the same list.
You can also do:
B=([A.copy()]*10)
However, it can produce references between the lists in B if their elements are complex object. But if you're using it for ints, strings and others basic stuffs it's going to work well.
A = [1,2,3]
B= []
n= 5
for i in range(5):
B.append(A)
where A is list, B is resultant list and n is number of rows