idiom for initial list of lists
Huaiyu Zhu
hzhu at users.sourceforge.net
Mon Sep 11 17:46:14 EDT 2000
Here's the timing results and program for various methods suggested here.
The winner (on my machine) is list_list. It is suprising that list_tuple
did worse, and that copy_list is the worst.
Results of first run:
append_range 0.9065
append_list 0.8199
append_xrange 0.7929
listcmprh_range 0.7849
listcmprh_list 0.7160
listcmprh_xrange 0.6666
lambda_range 0.6246
lambda_list 0.5487
lambda_xrange 0.5250
list_list 0.4702
list_tuple 0.7277
copy_list 1.3493
Results of second run:
append_range 0.9144
append_list 0.9064
append_xrange 0.8002
listcmprh_range 0.7854
listcmprh_list 0.7144
listcmprh_xrange 0.6560
lambda_range 0.6248
lambda_list 0.5471
lambda_xrange 0.5181
list_list 0.4775
list_tuple 0.7328
copy_list 1.3472
The test program:
"""
init_list.py - timing of different ways to init list of list
"""
def append_range():
S=[]
for i in range(n): S.append([])
def append_list():
S=[]
for i in [1]*n: S.append([])
def append_xrange():
S=[]
for i in xrange(n): S.append([])
def lambda_range():
S=map(lambda x:[], range(n))
def lambda_list():
S=map(lambda x:[], [1]*n)
def lambda_xrange():
S=map(lambda x:[], xrange(n))
def listcmprh_range():
S=[[] for x in range(n)]
def listcmprh_list():
S=[[] for x in [1]*n]
def listcmprh_xrange():
S=[[] for x in xrange(n)]
def list_list():
S=map(list, [[]]*n)
def list_tuple():
S=map(list, [()]*n)
from copy import copy
def copy_list():
S=map(copy, [[]]*n)
tests = [append_range, append_list, append_xrange,
listcmprh_range, listcmprh_list, listcmprh_xrange,
lambda_range, lambda_list, lambda_xrange,
list_list, list_tuple, copy_list]
#------------------------------------------------------------------
from time import time
def timeit(f):
_time = time()
f()
print "%-16s %.4f" % (f.__name__, time() - _time)
n = 100000
print n
#------------------------------------------------------------------
for f in tests:
timeit(f)
More information about the Python-list
mailing list