2

On dynamic creation of 2D array in Python3, values are not being updated in the following case:

no_col = 3
no_row = 4

arr = [[0 for x in range(no_col)] for y in range(no_row)] 

for i in arr[0]:
    i = 1

arr values

0 0 0
0 0 0
0 0 0
0 0 0

But on using range, values get updated

for i in range(no_col):
    arr[0][i] = 1

arr values

1 1 1
0 0 0
0 0 0
0 0 0

Why this happens ?

ArunJose
  • 1,999
  • 1
  • 10
  • 33
vasanths294
  • 1,457
  • 2
  • 13
  • 29

3 Answers3

2

This is because your for each

for i in arr[0]:
    i = 1

is equivalent to

for idx in range(len(arr[0])):
    i = arr[0][idx]
    i = 1

You can't modify the array in a for each loop because every iteration it creates a new variable and you are modifying the value of the new variable instead of the array

Take a look at this

Sanil Khurana
  • 1,129
  • 9
  • 20
2

There is a misunderstanding in what a = b does in Python.

It does not mean "modify a data, so that it is the same as b data".

Instead, it means: "from now on, use variable name a for referencing the same data which is referenced by varible b".

See in this example:

data = ['a', 'b', 'c']

x = data[0]  # x is now 'a', effectively the same as: x = 'a'

x = 'b'  # x is now 'b', but `data` was never changed

data[0] = 'm'  # data is now ['m', 'b', 'c'], x is not changed
data[1] = 'm'  # data is now ['m', 'm', 'c'], x is not changed

The same happens with the original code:

for i in arr[0]:
    # i is now referencing an object in arr[0]
    i = 1
    # i is no longer referencing any object in arr, arr did not change
zvone
  • 18,045
  • 3
  • 49
  • 77
0

In python the variables are not pointers.

what happens inside the loop is

1)for each element  in the array 
2)copy value of the array element to iterator(Only the value of the array element is copied and not the reference to its memory)
3)perform the logic for each iteration.

If you make any changes to the iterator object you are only modifying the copy of the variable's value and not the original variable(array element).

ArunJose
  • 1,999
  • 1
  • 10
  • 33