0

I'm fairly new to python so I'm sorry if this is a fairly noob question. But I'm writing a 2D list composed of data from .txt file with a for loop (all that code works), but the loop seems to be overwriting all my previously written data each time to passes though even though I'm

This isn't my actually code, but sum up the problem I'm having.

stuff = [[None]*3]*10

for index in range(10):
    stuff[index][2]=index

print(stuff)

[[None, None, 9],[None, None, 9],[None, None, 9],[None, None, 9],[None, None, 9],[None, None, 9],[None, None, 9],[None, None, 9],[None, None, 9]]

Why are all the values being returned as 9, why what do I have to do to get it to return as

[[None, None, 1],[None, None, 2],[None, None, 3],[None, None, 4],[None, None, 5],[None, None, 6],[None, None, 7],[None, None, 8],[None, None, 9]]
Remnet
  • 3
  • 3

2 Answers2

2

The reason that this is happening is because of your first line:

stuff = [[None]*3]*10

What this is actually doing is creating only 1 array of [[None]*3] and then referencing it 10 times.

So your array is actually similar to:

[[[None]*3], reference 0, reference 0, reference 0, reference 0, reference 0, reference 0, reference 0, reference 0, reference 0]

Change your first line to:

stuff = [[None]*3 for i in xrange(10)]

Which will create a unique element at each position within the array.

Serdalis
  • 10,296
  • 2
  • 38
  • 58
  • Thank you for the explanation, I didn't realize that's how lists worked in Python. – Remnet Feb 13 '14 at 19:59
  • Huh, any reason why is works like this? One would think it would be the same behaviour as making the 1D array. – Swedgin Nov 03 '20 at 12:28
  • @Swedgin The behavior is the same for both but None isn't mutable so doesn't suffer from the same potential errors. – Serdalis Nov 04 '20 at 00:11
  • @Serdalis Thanks for the reply. Though I came here due to making an array like this `arr = [[0] * 10] * 2`, which has the same behaviour as OP's question. In other words, why does python makes references in the 2D example and not in the 1D example? But this is probably a question on itself. Or I should delve into the docs. – Swedgin Nov 04 '20 at 08:43
  • 1
    @Swedgin It's cause `0` is not mutable so you can't change it, in python `0` is a label to the value `0`. If you make a 1D array of mutable types and change the mutable type you will have the same issue as the 2D array. – Serdalis Nov 04 '20 at 10:16
1

You are putting the same exact array in the list ten times. Updating one of the arrays is updating all of them. Try:

stuff = [[None]*3 for i in xrange(10)]
Stephen
  • 215
  • 2
  • 7