1

Possible Duplicate:
In Python, what is the difference between “.append()” and “+= []”?

In Python, I've recently noticed that you can append list items in two ways:

a.append(1)
a += [1]

I like using the second approach because it is more readable for me. Are there any downsides to using it?

Community
  • 1
  • 1
Blender
  • 275,078
  • 51
  • 420
  • 480
  • I'd say the second is more error-prone. Are you adding the number `1` or the list `[1]`? `.append()` and `.extend()` make this distiction clear, while also not requiring the confusing extraneous brackets. – Kurt Spindler Mar 14 '12 at 00:33
  • AFAICT, the bracket notation is identical to `a.extend([1])`, which acts just like `a.append(1)`. The only downside is that the second approach is about twice as slow. – Blender Mar 14 '12 at 00:36
  • But `.append()` and `.extend()` are even easier to confuse. Personally I find `+= [1]` absolutely clear. It's whatever you're used to, I guess... – alexis Mar 14 '12 at 00:39

3 Answers3

5

Those two methods aren't quite equivalent. The += method:

a += [1]

requires that you first create a new list containing the single element 1, tack it on to the list a, then discard the single-element list. This would be more equivalent to:

a.extend([1])

You will likely find that a.append(1) does less work, since it does not need to create a single-element list which it's just going to throw away in the next step.

Greg Hewgill
  • 890,778
  • 177
  • 1,125
  • 1,260
2

Check out the interesting results here. Short version: append is faster.

Community
  • 1
  • 1
hochl
  • 11,784
  • 10
  • 53
  • 83
0

It depends on the Python implementation, but append will never be slower than the second variant.

a += [1] creates a temporary list with one element. Additionally, the += operator has to perform some extra work to determine the size of the new list. A good Python implementation may reduce the overhead by not actually constructing the list [1] in memory.

As with virtually every performance question, it doesn't matter unless your code is really performance-critical. With cpython 2.7, I measured the following values:

>>> import timeit
>>> timeit.timeit('l = []\nfor i in range(200):\n\tl.append(1)\n')
27.95561385154724
>>> timeit.timeit('l = []\nfor i in range(200):\n\tl += [1]\n')
37.52841401100159
phihag
  • 263,143
  • 67
  • 432
  • 458