tags:

views:

125

answers:

3

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.

+5  A: 

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?

Borealid
Thanks. So how do I force python to give me a unique array within each cell of the parent array?
Tyler
`M = [[] for _ in range(24*60/5)]` is the simplest way (it's a list comprehension).
Amber
Excellent. Thank you!
Tyler
+4  A: 

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".

EOL
A: 

I don't want to be an asshole but 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".

Steven Mohr
I got that solution from StackOverflow.
Tyler
It's just easier to learn this rules to write good, pythonic code when you're a beginner ...
Steven Mohr