giffy
giffy

Reputation: 119

Why does a list comprehension not append in python

I create a list comprehension that tries to imitate Matlab Cell of 3x3 Matrices.

kis= [ np.zeros(shape=(3,3)) for t in range(1, 5) ]

This is just like a cell in Matlab having five 3x3 zero matrices. I can access them as

kis[0]
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])

I can modify them as

>>> kis[0][0][1]=2
>>> kis[0]
array([[ 0.,  2.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])
>>> kis[0][0][1]
2.0

Right now there are 5 elements, say i wish to add a sixth element.

kis.append(np.zeros(shape=(3,3)))

When i try to access the sixth cell element which is supposed to be a 3x3 matrices of zeros, i have this error:

>>> kis[5]

Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    kis[5]
IndexError: list index out of range

So how to append more 3x3 matrices into the list? Why the above method does not work? The above code is in Python 2.7.9.

Upvotes: 0

Views: 95

Answers (2)

Marcin Fabrykowski
Marcin Fabrykowski

Reputation: 619

>>> kis= [ np.zeros(shape=(3,3)) for t in range(1, 5) ]
>>> len(kis)
4

so last index is 3. when you:

>>> kis.append(np.zeros(shape=(3,3)))
>>> len(kis)
5

last index is 4.
so, kis[5] is out of range

Upvotes: 1

user2357112
user2357112

Reputation: 280973

kis= [ np.zeros(shape=(3,3)) for t in range(1, 5) ]
#                             only 4 things ^^^^

If you want 5 elements, you want range(5).

Upvotes: 3

Related Questions