1
A=???????????
print(A)
A[3][0]=5
print(A)

What can you put in the ?'s to make it output:

[[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]

[[1], [5], [1], [5], [1], [5], [1], [5], [1], [5]]

Hint: you can answer this question with an answer exactly as long as the number of ?'s. I tried the following.

A=[[1] for i in range(11)]

But this only gives me the first output. How can I make it so that I get the output given when A[3][0]=5?

khelwood
  • 55,782
  • 14
  • 81
  • 108
A.Ell
  • 31
  • 2

1 Answers1

2

If you construct your list as

A = [[1],[1]]*5

then it contains 5 references to two lists. It's like saying:

X = [1]
Y = [1]
A = [X, Y, X, Y, X, Y, X, Y, X, Y]

Initially this looks like:

[[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]

Then altering

A[3][0]=5

means you're altering the list that lies in every alternate position in A, giving you

[[1], [5], [1], [5], [1], [5], [1], [5], [1], [5]]
khelwood
  • 55,782
  • 14
  • 81
  • 108