1

Possible Duplicate:
Python list confusion

This is a quiestion about list of python. (My programming environment is SL4A with python)

I want a list below with inputted number "n".

[ ['a'] , [] , [] , [] ] # (this example is the list when n =4)    <- the list I want

So, I wrote a source-code below.

n = input()
array = [[]]*n
array[0].append('a')
print array

However, I can' get an output above, but also get a list as like...

[ ['a'], ['a'], ['a'], ['a'] ] #  <- wrong list

So, I have two questions.

  1. Please tell me a source-code which is give me a list what I want.
  2. Why does the source-code give me the wrong list?
Community
  • 1
  • 1
aaaaa0a
  • 127
  • 2
  • 13
  • Thanks for editting my question and telling me a past question I should comfirm before I post this question. – aaaaa0a Nov 19 '12 at 12:56

3 Answers3

3

You should use

array = [[] for x in range(n)]

Otherwise you get 4 references to the same list

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
0

When you do

array = [[]]*n

you will get a list with n same links. That is why when you edit one of the element you edit every element. To get rid of this just use something like this

for i in range(0, 4):
    array1.append([])
    array2+=[]
Gavelock
  • 77
  • 8
0

python 3.2:

n = input()
array = [[] for i in range(n)]
array[0].append('a')
print array
Community
  • 1
  • 1
raton
  • 418
  • 5
  • 14