Problem to read from array
Laura Creighton
lac at openend.se
Sat Nov 21 09:22:55 EST 2015
In Python we don't write while loops that often.
instead we do:
for i in range(NumberOfColumns):
for j in range(NumberOfRows):
do_something()
But for the particular case that you are after, constructing lists,
we have something even neater -- list comprehensions.
So you might write:
>>> newarray=[]
>>> for i in range(3):
... newarray[i] = i
And this would not work.
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
IndexError: list assignment index out of range
At this point you might get a bit frustrated. Python is happily telling
you that you don't have a newarray[0][0] which is hardly news to you who
was trying to initialise the thing.
The trick is to initialise it with a list comprehension.
You write one like this:
[ calculate_something() for i in range(LIMIT)]
This works:
>>> newarray = [i for i in range(3)]
>>> newarray
[0, 1, 2]
>>>
As does
>>> newarray = ["hello" for i in range(3)]
>>> newarray
['hello', 'hello', 'hello']
You can even build your lists with a condition:
>>> even_numbers=[x for x in range(11) if x % 2 == 0]
>>> even_numbers
[0, 2, 4, 6, 8, 10]
You are not limited to one dimentional arrays (lists) here. You
can have much more complicated expressions as the calculate_something.
>>> newarray =[[ [x+2000, y*y] for x in range(3)] for y in range(5)]
>>> newarray
[[[2000, 0], [2001, 0], [2002, 0]], [[2000, 1], [2001, 1], [2002, 1]],
[[2000, 4], [2001, 4], [2002, 4]], [[2000, 9], [2001, 9], [2002, 9]],
[[2000, 16], [2001, 16], [2002, 16]]]
Which leads us to a particularly useful construct:
>>> emptyarray =[[ [] for x in range(3)] for y in range(5)]
>>> emptyarray
[[[], [], []], [[], [], []], [[], [], []], [[], [], []], [[], [], []]]
Bingo. Now you won't have any index errors when you try to append
to your x,y values.
Hope this is useful.
Also, there is the tutor mailing list
https://mail.python.org/mailman/listinfo/tutor
which you might be interested in, where we discuss things like this.
Peter Otten is there, too.
Laura
More information about the Python-list
mailing list