-2

I have an array which contains again arrays. Now I would like to have every inside-array twice in my main-array.

Unfortunately when going the way I did, I messed the index up and haven't been able to modify a specific element in the array (example: Payliketable[2][5]) because this is then there serval times.

How can I duplicate every inside-array while giving each it's own "index"?

i = 1
while i < len(PaylikeTable):
        PaylikeTable.insert(i,PaylikeTable[i])
        i += 2

As said the array "Payliketable" again consists out of arrays.

scenatic
  • 51
  • 4

3 Answers3

0

Did you mean to duplicate every element in an array ? For that just add array with same array

   list1=[[1,2,3],[5,6,7]]
   list1+list1 will get
   [[1,2,3],[5,6,7],[1,2,3],[5,6,7]]
abu
  • 11
  • 2
  • Unfortunately this way, there is still the problem, that in the "doubled_list" do have the duplicates the same index. For example if I modify doubled_list[3][5] then it hit's both duplicates – scenatic May 02 '19 at 15:41
0

First off, never modify a list while iterating it. There should be better ways to do it.

To understand what I explained, check the current list after each iteration manually with a digestible starting list like [[1], [2], [3]]. You would easily see what is going wrong.

Assuming there are no memory constraints its better to make one more list:

doubled_list = []
for item in single_list:
    doubled_list.extend([list(item), list(item)])

using list() creates a copy of item, using item directly will refer to the same item instance.

More reading: Copying a list

ybl
  • 1,510
  • 10
  • 16
  • Unfortunately this way, there is still the problem, that in the "doubled_list" do have the duplicates the same index. For example if I modify doubled_list[3][5] then it hit's both duplicates – scenatic May 02 '19 at 15:41
  • Correct, I did not understand you requirement. I've edited with an explanation – ybl May 02 '19 at 16:02
0

Lists are mutables. See here for more info about mutables and immutables.

To create a copy of a mutable (and not just a reference to it), the best way is to use the copy module.

import copy

PaylikeTable = [[1, 2, 3], [2, 4, 6], [5, 6, 2]]

i = 0
lpt = len(PaylikeTable)*2
while i < lpt:
    PaylikeTable.insert(i, copy.deepcopy(PaylikeTable[i]))
    i += 2

print(PaylikeTable) #the doubled list
#[[1, 2, 3], [1, 2, 3], [2, 4, 6], [2, 4, 6], [5, 6, 2], [5, 6, 2]]

PaylikeTable[3][1] = 99

print(PaylikeTable) #only element 3, 1 is edited.
#[[1, 2, 3], [1, 2, 3], [2, 4, 6], [2, 99, 6], [5, 6, 2], [5, 6, 2]]
Valentino
  • 7,291
  • 6
  • 18
  • 34