Preallocate? -- potentially brain dead question about performance
Jan Danielsson
jan.m.danielsson at gmail.com
Mon Feb 26 20:30:18 EST 2007
bearophileHUGS at lycos.com wrote:
>> 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.
What an idiot I am.. Yes, I know that.. And I actually *had* working
code laying around, but rather than opening it and copy-and-pasting, I
simply rewrote it. I obviously meant:
newlist[i] = int(e[0])
> 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)
...completely avoiding the design issue I raised altogether. Thanks!
Exactly what I was hoping for! :-)
--
Kind regards,
Jan Danielsson
More information about the Python-list
mailing list