Understanding Differences Between Python Append() and = Operator on Lists
The append() method and the = operator behave differently when operating on lists. append() adds the given element to the end of the list, while = concatenates the elements of the operand list to the existing list.
Consequences of Using =
Using = with a list as an operand results in a new list that combines the original list with the operand list's elements. For example:
<code class="python">c = [1, 2, 3] c += c print(c) # [1, 2, 3, 1, 2, 3]</code>
Recursion with append()
In contrast, append() appends the list itself as a single element, which leads to infinite recursion if the list is added to itself. This occurs because the list's last element, accessed through c[-1], now refers to the list itself, creating a recursive loop.
<code class="python">c = [1, 2, 3] c.append(c) print(c) # [1, 2, 3, [...]] # infinite recursion</code>
Alternative Option: extend()
To append the elements of one list to another, use the extend() method. It modifies the original list in-place, unlike = which creates a new list:
<code class="python">c = [1, 2, 3] c.extend(c) print(c) # [1, 2, 3, 1, 2, 3]</code>
The above is the detailed content of How Do Python\'s `append()` and ` =` Operators Differ When Used on Lists?. For more information, please follow other related articles on the PHP Chinese website!