Dynamic or not?
Marc 'BlackJack' Rintsch
bj_666 at gmx.net
Thu Dec 13 10:24:02 EST 2007
On Thu, 13 Dec 2007 06:51:23 -0800, rishiyoor wrote:
> When you say python automatically allocates memory, what would you do
> if you don't know the size of the list of, say for example, the
> nearest pairs between the two groups. I would probably iterate over
> all the pairs and create a new list. I did a similar operation in
> another program, but I had to initialize the list (statically) with x
> = [0]*50 before I could use it in the for loop.
Only if you used an index instead of starting with an empty list and
appending values to it. Or in simple cases a list comprehension might
replace a ``for`` loop.
"Bad" and "unpythonic" example:
new = [0] * len(old)
for i in xrange(len(old)):
new[i] = do_something(old[i])
Better written as:
new = list()
for item in old:
new.append(do_something(item))
Or as list comprehension:
new = [do_something(item) for item in old]
Or:
new = map(do_something, old)
Ciao,
Marc 'BlackJack' Rintsch
More information about the Python-list
mailing list