1

I have the following code snippet:

d = [[0,558,437,142,45,290], [558,0,232,500,600,523], [437,232,0,408,492,572], 
 [142,500,408,0,180,197], [45,600,492,180,0,254], [290,523,572,197,254,0]]

for row in d:
    for elem in row:
        elem = elem * 2
print d[0][1]
print '\n'

Why does it not print the new value, it still prints 558

Edgar P
  • 61
  • 7

4 Answers4

5

elem = elem * 2 modifies the value of a variable named elem. This variable has nothing to do with the list other than its initial value came from a list element.

To do what you want, you need indexes into the array. Alternatively, you can use the map() function. However, this will only create a new list with the new values rather than changing the values of the original list.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
3

You are assigning a new value to the variable elem. This does not effect the list. Instead try this:

d = [[0,558,437,142,45,290], [558,0,232,500,600,523], 
[437,232,0,408,492,572], 
 [142,500,408,0,180,197], [45,600,492,180,0,254], [290,523,572,197,254,0]]

for row in d:
    for index in range(len(row)):
        row[index] *= 2
print d[0][1]
print '\n'

Notice that I use index for the index to the element instead of accessing the element itself.

zondo
  • 19,901
  • 8
  • 44
  • 83
2

Aside of the "why" as mentionned in other answers, here is how you can achieve this using list comprehensions:

d = [[0,558,437,142,45,290], [558,0,232,500,600,523], [437,232,0,408,492,572], 
 [142,500,408,0,180,197], [45,600,492,180,0,254], [290,523,572,197,254,0]]

for i, el in enumerate(d):
  d[i] = [row * 2 for row in el]

print(d)
Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67
2

You probably want something like this instead:

double_d = [[elem * 2 for elem in row] for row in d]

Using list comprehensions is more idiomatic Python.

Paulo Scardine
  • 73,447
  • 11
  • 124
  • 153
  • 2
    It's worth pointing out that this does not change the elements of the original list. – Code-Apprentice Feb 02 '16 at 21:39
  • Well, instead of using a new variable `double_d` the OP can assign the result to `d` in order to destroy the original information. – Paulo Scardine Feb 02 '16 at 21:54
  • Of course. Either way, this creates a new list rather than changing the elements of the existing list. I'm sure you know this. I'm pointing it out for the benefit of the OP and future readers. – Code-Apprentice Feb 02 '16 at 22:11