February 19th, 2005, 04:14 PM
Which is better append or a[len(a):] = [x] ?
I know both are equivalent in term of effect but is one or the other better in terms of standards, speed or any other considerations ?
February 19th, 2005, 05:28 PM
Use append . Besides being the fastest aList.append() is also much easier on the eyes and makes it far more obvious what your code is doing.
Heres a quick benchmark for the two expressions using the timeit module (see the "Tips, Tricks, Inspiration etc." thread at the top of the forum).
Note: this was done using Python 2.4 under Mac OS X 10.3.8 on a 1Ghz G4 iBook with 1GB RAM.
>>> import timeit
>>> a = 
>>> timeit.Timer('a[len(a):] = ', 'from __main__ import a').timeit()
>>> b = 
>>> timeit.Timer('b.append(0)', 'from __main__ import b').timeit()
February 21st, 2005, 02:51 AM
In my personal opinion, I think that append would be better, but, thats just me
February 21st, 2005, 09:06 AM
It seems there is no reason not to use append
The only thing I could see why I would use the slice operator is to get used to it ...
So I am going to stick with append
February 25th, 2005, 09:30 PM
You'd use the append method here as it's simpler. The append method is generally better for this, as you
can assign it to a variable (Python has higher order functions) or pass it in as a function parameter, eg:
Slicing is useful elsewhere, for instance if you want to remove a chunk of mylist:
# Really bad way of building a list of integers - for demo purposes only!
def compose(f, values):
for x in values:
mylist = 
f = mylist.append
values = range(10)
Or make a shallow copy:
Or insert another list:
mylist2 = mylist[:]
Note that this is different from the insert method:
mylist[4:4] = range(10,20)
Note also that there is an alternative to the append method:
mylist = range(10)
mylist += range(11,20)