Initialize an array of arrays:
M = [[]]*(24*60/5)
Append the number 2 to the 51st array in M
M[50].append(2)
What is in M?
...
[2]
[2]
[2]
[2]
[2]
[2]
[2]
[2]
...
Every element in M is the array [2]
What am I missing? I suspect that every [] that I initially initialize is a reference to the same space in memory.
3 Answers 3
You did create an array of arrays. But you then assigned the same [] to every one of its entries.
It's not that every time you call [] it gives you the same array - it's that you only called [] once.
Get it?
Yes, you got it, as Borealid pointed out.
If you want many times a different list, you can do:
M = [[] for _ in range(24*60/5)]
The _ is just a regular variable name (variables can start with an underscore), but it tells readers of the code "I'm an unimportant variable, with no special meaning associated to it".
Comments
Take a look at http://www.python.org/dev/peps/pep-0020/.
The construct you liked to use is really hard to read and "Readability counts".