Preallocate? -- potentially brain dead question about performance

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Mon Feb 26 18:44:20 EST 2007


Jan Danielsson:
>    newlist = [ None ] * len(mylist)
>    for i in range(len(mylist)):
>       newlist.append(int(e[0]))

Note that this appends after the Nones, not over them. And note that
here the name 'e' is undefined.

The most used idiom for that is:

newlist = [int(e[0]) for e in mylist]

Or better lazily if you want to create a set, avoiding the list
creation:

newlist = set(int(e[0]) for e in mylist)

Bye,
bearophile




More information about the Python-list mailing list