Problem
As we all know, in Python, The + operator can be used on the list, and the + operator only needs the second operand to be iterated (Original: iterable. @ Justjavac), then
+ The operation can obviously be performed on "ha.
The Code is as follows:
>>> x = []>>> x += "ha">>> x['h', 'a']>>> x = x + "ha"Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: can only concatenate list (not "str") to list
Answer
When we use + = On the list, it is actually equivalent to calling the extend () function, rather than using
+.
- You can call extend () on an iterable object ().
- However, when you use +, the other operand must be list ).
Why is Python so strange? It may be due to performance considerations. When you call +, a new object is created and all the content is copied. However, when you call the extend () function, you can use the existing space.
This produces another side effect: If you write x + = Y, you will see the changes in other references to the list. However, if you use X = x + y, no.
The following code illustrates this:
>>> X = ['A', 'B'] >>> y = ['C ', d'] >>>> z = x >>> x + = y >>> Z ['A', 'B', 'C ', 'D'] // Z has also changed >>> x = ['A', 'B'] >>> y = ['C ', d'] >>>> z = x >>> x = x + y >>> Z ['A', 'B'] // Original Value of the Z Function
References
Python source code
For list.
Python: + = source code:
static PyObject *list_inplace_concat(PyListObject *self, PyObject *other){ PyObject *result; result = listextend(self, other); if (result == NULL) return result; Py_DECREF(result); Py_INCREF(self); return (PyObject *)self;}
Python: + source code:
static PyObject *list_concat(PyListObject *a, PyObject *bb){ Py_ssize_t size; Py_ssize_t i; PyObject **src, **dest; PyListObject *np; if (!PyList_Check(bb)) { PyErr_Format(PyExc_TypeError, "can only concatenate list (not \"%.200s\") to list", bb->ob_type->tp_name); return NULL; } // etc ...
Original article: Python
-If X is list, why does x + = "ha" work, while X = x + "ha" throw an exception?
In
In python, if X is a list, why does x + = "ha" Run While X = x + "ha" throw an exception?
Translator: justjavac