0

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.

SilentGhost
322k67 gold badges312 silver badges294 bronze badges
asked Jul 13, 2010 at 6:01

3 Answers 3

5

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?

answered Jul 13, 2010 at 6:03
Sign up to request clarification or add additional context in comments.

2 Comments

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

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

answered Jul 13, 2010 at 6:09

Comments

0

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

p.campbell
101k71 gold badges265 silver badges326 bronze badges
answered Jul 13, 2010 at 7:05

2 Comments

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.