I stumbled into something that surprised me while writing some Python code. I was considering two ways of duplicating a list, then adding one more element to the duplicate:
# I thought this would be clean-looking but slow since it creates an extra one element list, ['foo'] mylist = range(4) newlist_0 = mylist + ['foo'] print newlist_0 # [0, 1, 2, 3, 'foo'] # I thought this would be faster newlist_1 = list(mylist) newlist_1.append('foo') print newlist_1 # [0, 1, 2, 3, 'foo'] Surprisingly the first way is not only nice to look at but also faster. I ran:
import timeit for stmt in ['newlist_0 = mylist + ["foo"]', 'newlist_1 = list(mylist); newlist_1.append("foo")']: print "For statement {:50} timeit results are {}".format(stmt, timeit.repeat(setup='mylist = range(4)', stmt=stmt)) and got this output:
For statement newlist_0 = mylist + ["foo"] timeit results are [0.29012012481689453, 0.3021109104156494, 0.32175779342651367] For statement newlist_1 = list(mylist); newlist_1.append("foo") timeit results are [0.39945101737976074, 0.39692091941833496, 0.38529205322265625] Momentarily I stumbled onto this question discussing the fact that list(lst) is slower than lst[:] for copying a list, but switching to using [:] to copy mylist doesn't change anything.
+nor["foo"]involve function calls under the hood, butappenddoes?