Which is more pythonic?
list.append(1)
or
list += [1]
Which is more pythonic?
list.append(1)
or
list += [1]
list.append(1)
is faster, because it doesn't create a temporary list object.
Since there's also
list.extend(l)
which appends all elements of the given list, I would use
list.append(1)
for symmetry and readability's sake.
These are two different operations, what you are doing with += is the extend operation. Here is what Python documents have to say about this:
list.append(x): Add an item to the end of the list; equivalent to a[len(a):] = [x].
list.extend(L): Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.
So in += you provide a list, in append you just add a new element.
While most people here are preferring the append option, I personally prefer the other one because it looks nicer even though it may be slower (or maybe its optimized).
Beautiful is better than ugly.
When you write lots of Python code, I don't usually see something like this:
list.append(1)
It's more like this:
somecollectionname.append(anotherelementname+5*10)
So to me at least, it is nicer to see:
somecollectionname += [anotherelementname+5*10]
Because its easy to recognize at a glance that you are adding to a list. Having said that, I sometimes find myself using both forms.
If you've got a single element, a
, that you want to add to your list l
, then putting a
into its own list and extending l
with it seems like adding unnecessary complexity. I would thus prefer
l.append(a)
over
l += [a]
If a
is already a list, then choosing
l += a
or
l.extend(a)
is a matter of preference, IMO. On the other hand, if you're going to be doing a lot of extends, you can get a performance boost by "hoisting" the method lookup:
extend = l.extend
for sublist in bunch_of_lists:
extend(sublist)
Finally, I think that the append operation isn't used too often in Pythonic code, because append is used very often in "accumulator" idioms, where I'd expect a more experienced Python programmer to use a list comprehension/etc.
So instead of:
l = []
for a in numbers:
l.append(str(a))
You'd probably see:
l = [str(a) for a in numbers]
or
l = map(str, numbers)