Preallocate? -- potentially brain dead question about performance

Jan Danielsson jan.m.danielsson at gmail.com
Mon Feb 26 18:10:34 EST 2007


Hello all,

   I have a list which contains a bunch of tuples:

   mylist = [ ('1', 'Foobar'), ('32', 'Baz'), ('4', 'Snorklings') ]

   (The list can potentially be shorter, or much longer). Now I want to
take the first element in each tuple and store it in a list (to use in a
Set later on).

   Which would You prefer of the following:

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

   ..or..

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


   To me, the second one is more appealing, when I think in terms of
risk of memory fragmentation, etc. But since Python is such a high level
language, I'm not sure my traditional reasoning applies.

-- 
Kind regards,
Jan Danielsson



More information about the Python-list mailing list