Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading