'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?
Solution 1:[1]
A list of list is not a matrix, it is a … list of list.
Let's decompose foo[:][0] :
foois a name pointing to a list[:]is a first "subscript access" to the list pointed byfoo. 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.
Solution 2:[2]
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
Solution 3:[3]
In the source of list code,List is a structure with a double pointer which point to the space of array,and a length for list.To your list foo[:][0], foo[:] could writting like that foo[start:end], and , if you are not setting the value for start and end,it would auto set -inf and inf.So,foo[:] have all the sub_List.foo[:][0] is one of your sub_List.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Niko B |
| Solution 2 | inquirer |
| Solution 3 |
