Skip to content
Advertisement

Indexing 2d lists in Python: Lengths in each dimension are not what I expect

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement