-1

I was trying to solve a problem but I encounter a problem.

When I do this:

arr=[[[0]*5]*5]

I get this:

[[[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]]

But when I try to select an element:

arr[0][0]

It returns this:

[0, 0, 0, 0, 0]

Why?

MSeifert
  • 145,886
  • 38
  • 333
  • 352

5 Answers5

6

Simply remove the outer []:

arr=[[0]*5]*5

However that's a bad way to create nested lists. It's better to use:

arr = [[0 for _ in range(5)] for _ in range(5)]

That way you don't get bitten by the "shared reference problem".

MSeifert
  • 145,886
  • 38
  • 333
  • 352
1
arr = [[0]*5]*5 #will work

so arr = [[[0]*5]*5] is equivalent to arr = [your required arr] inside another list

Chava Geldzahler
  • 3,605
  • 1
  • 18
  • 32
Sid
  • 451
  • 3
  • 9
0

You have an extra pair of square brackets. Try arr = [[0]*5]*5.

Cuber
  • 713
  • 4
  • 17
0

You have an extra pair of brackets.

Try instead:

arr = [[0] * 5] * 5

We can prove this by breaking down your code:

arr= [ [ [ 0 ] * 5 ] * 5]

We condense the innermost layer to be: arr = [ [ [0]*5 ] * 5] which returns:

[ [[0, 0, 0, 0, 0]] * 5]

Now the inner portion returns:

[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

As your desired result is now present, we now see that the remaining brackets are no longer needed.

Anthony Pham
  • 3,096
  • 5
  • 29
  • 38
0

because you're not getting

[[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]

you're getting

[[[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]]

omit the extra brackets.

arr=[[0]*5]*5
derelict
  • 2,044
  • 10
  • 15