0

Possible Duplicate:
Python List Index

result=[range(3)]*2
for i in range(len(result)):
    result[i][2]=4*i
print result

I would expected [[0, 1, 0], [0, 1, 4]]

Why do I get [[0, 1, 4], [0, 1, 4]]

Thank you!

Community
  • 1
  • 1

2 Answers2

0

When you do [range(3)] * 2, it makes a list with two references to the same list inside, so modifying result[0] and result[1] each modify both.

Use [range(3) for i in range(2)] to make a list with two different results of range(3) in it.

Danica
  • 28,423
  • 6
  • 90
  • 122
  • your suggestion works very well. Thank you! why would [range(3)]*2 make a list with two references to the same list, and modify each will modify both? just doesn't make sense to me... – user2022404 Jan 29 '13 at 17:03
0
  • List "result" is: [[0, 1, 2], [0, 1, 2]]
  • Your iteration is: "for i in range(len(result))"
  • len(result) is: 2
  • range(2) is: [0,1]

meaning:

first time: result[0][2]=4*0

second time: result[1][2]=4*1

which gives you the result [[0, 1, 4], [0, 1, 4]]

This is what is doing step by step.

If you add a "break" to the iteration you see the result is [[0, 1, 0], [0, 1, 0]]

The "result" list works by reference. When it is called, it is pointing to the same object.

danielcorreia
  • 2,108
  • 2
  • 24
  • 36