List Extending Strange Behavior

Found an interesting thing in Python (2.7) that was never mentioned before.

It:

a = [] a += "a" 

works and the result is:

 >>> a >>> ["a"] 

But

 a = [] a = a + "a" 

gives

 >>> TypeError: can only concatenate list (not "str") to list 

Can someone explain why? Thank you for your responses.

+6
python list
source share
2 answers

Python distinguishes between the + and += operators and provides separate bindings for this; __add__ and __iadd__ . The list() just provides a different implementation for the latter.

For lists, it is more efficient to implement them separately; __add__ should return a whole new list, and __iadd__ could just extend self and then return self .

In C code, __iadd__ implements list_inplace_concat() , which simply calls listextend() or, in python code, [].extend() . The latter takes any sequence, by design.

On the other hand, the __add__ method, introduced in C by list_concat , accepts only list , possibly for efficiency; it can loop directly on the internal C array and copy elements to a new list.

In conclusion, the reason __iadd__ accepts any sequence, because when PEP 203 (the added add clause) was implemented, for lists it was easiest to reuse the .extend() method.

+11
source share

If a is a list, a + x only works if x also a list, while a += x works for any iterative x .

The following may help to understand this:

 In [4]: a = [] In [5]: a += "abc" In [6]: a Out[6]: ['a', 'b', 'c'] 

The key is that "a" and "abc" are iterable, which allows you to use them on the right side += .

This does not work for + , because the latter requires both operands to be of the same type (see manual ).

To write the same thing with + , you need to expand iterable:

 In [7]: a = [] In [8]: a = a + list("abc") In [9]: a Out[9]: ['a', 'b', 'c'] 

In other words, += is more general than + when applied to lists.

+9
source share

All Articles