Home > Back-end >  Indexing 2d lists in Python: Lengths in each dimension are not what I expect
Indexing 2d lists in Python: Lengths in each dimension are not what I expect

Time:04-27

If I create a 2d list:

In [1]: foo = [[None]*10]*5

In [2]: foo
Out[2]: 
[[None, None, None, None, None, None, None, None, None, None],
 [None, None, None, None, None, None, None, None, None, None],
 [None, None, None, None, None, None, None, None, None, None],
 [None, None, None, None, None, None, None, None, None, None],
 [None, None, None, None, None, None, None, None, None, None]]

In [3]: len(foo)
Out[3]: 5

I would expect the list in the first element of foo to be accessed with foo[0] or foo[0][:]. Thus it's length is 10, as expected:

In [4]: len(foo[0][:])
Out[4]: 10

type(foo[:][0]) returns "list". I would expect this to be a list constructed of the 0th elements from each "sublist" of foo. Thus it should be of length 5. However, this isn't the case:

In [5]: len(foo[:][0])
Out[5]: 10

What am I missing here/ what do I not understand?

CodePudding user response:

A list of list is not a matrix, it is a … list of list.

Let's decompose foo[:][0] :

  • foo is a name pointing to a list
  • [:] is a first "subscript access" to the list pointed by foo. Specifically you are getting a copy of the original list by slicing it with no indexes given
  • [0] is a second "subscript access" to the result of the first.

You are accessing the first element of a copy of foo.

CodePudding user response:

Try converting an array to numpy, it works much faster and is more convenient in accessing elements.

import numpy as np
foo = np.array([[None]*10]*5)
print(foo.shape)
print(len(foo[0, :]))#10
print(len(foo[:, 0]))#5

CodePudding user response:

Maybe it just like (foo[:])[0],foo[:] have all sub_list,and,foo[:][0] is mean getting one of the sub_list.

  • Related