0

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?

kgdc
  • 85
  • 1
  • 1
  • 10

4 Answers4

2

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.

online example

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.

online example

* at least in terms of this input

Baldrickk
  • 4,291
  • 1
  • 15
  • 27
  • when I used trying this method,there are two for loop then couldn't the code be slowed down? and "[A]*n" is this method also same to your run time complexity? – kgdc Jun 28 '17 at 19:38
  • 1
    @kgdc `[A]*n` results in `n` 'copies' of the same list. Each copy actually being a reference, and so not independent. This code produces a deep copy (copying all the elements) – Baldrickk Jun 28 '17 at 19:43
0

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.

JohanL
  • 6,671
  • 1
  • 12
  • 26
  • what are the deferences of comparing with above answer. "B = [[i for i in A] for n in range(10)]" – kgdc Jun 28 '17 at 20:40
  • Well, the syntax for one thing. I think it looks a little bit more readable to keep it at only one layer of list comprehension. Then I would guess - but I am not sure - that my suggestion should be a bit quicker, as it allows for the whole list to be copied in one go, instead of built element by element (with the overhead that can incur when looking at close-to-metal memory allocation et c.). – JohanL Jun 28 '17 at 20:46
0

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.

matteo_c
  • 1,990
  • 2
  • 10
  • 20
-2
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

Saurabh kukade
  • 1,608
  • 12
  • 23