0

My question is:

Lets say I have N arrays: arr0, arr1, arr2,... arrN (edit: actually N+1 arrays, but it doesn't matter) .

I want to insert to the first member of all the arrays values, in the same line, like this:

[arr0[0], arr1[0], arr2[0]... arrN[0]]=[0,1,2,3....N]

I would expect that after this line arr0[0] will be 0, arr1[0] will be 1 etc.

but, for some reason, what happends is arr0[0]=arr1[0]=arr2[0]=...=arrN[0]=N

Any idea why, and what can I do to fix it?

Thanks in advance.

Idos
  • 15,053
  • 14
  • 60
  • 75
Binyamin Even
  • 3,318
  • 1
  • 18
  • 45
  • The code you posted does work as expected (for lists, NumPy arrays and `array.array`s). Can you post more code so the problem is reproducible? – unutbu Dec 20 '15 at 11:12
  • I initiated all the arrays with 'None' 's - maybe that could be the problem? – Binyamin Even Dec 20 '15 at 11:16

2 Answers2

2

Based on your description of the symptom, I'm going to guess you defined the lists like this:

arr0, arr1 = [[None]]*2

In that case, both arr0 and arr1 refer to the exact same list, because [xyz]*2 produces the list [xyz, xyz] where xyz is the exact same object listed twice.

So when Python encounters [arr0[0], arr1[0]] = [10, 20] it first assigns

arr0[0] = 10

and then

arr1[0] = 20

but since arr0 and arr1 both refer to the same list, the first element in both lists is assigned-to twice:

In [46]: arr0, arr1 = [[None]]*2

Note that assignment to arr0 affects arr1:

In [47]: arr0[0] = 10

In [48]: arr1
Out[48]: [10]

Note that assignment to arr1 affects arr0:

In [49]: arr1[0] = 20

In [50]: arr0
Out[50]: [20]

Since the assignments are evaluated from left to right, the right-most assignment is last and so it is that assignment which ultimately affects both lists arr0, arr1.


To fix the problem: Use

arr0, arr1 = [None], [None]

or

arr0, arr1 = [[None] for i in range(2)]

since in both cases, arr0 and arr1 get assigned to different lists.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
0

You can use enumerate like this:

for index, value in enumerate([arr0, arr1, arr2... arrN]):
    value[0] = index

But of course, this would fail with an IndexError if any of your arrays is an empty array. To fix that, you need to do this:

for index, value in enumerate([arr0, arr1, arr2... arrN]):
    if not value:
        value = [index]
    else:
        value[0] = index

You may read about enumerate here.

Indradhanush Gupta
  • 4,067
  • 10
  • 44
  • 60