Home  >  Article  >  Backend Development  >  How Do Python\'s `append()` and ` =` Operators Differ When Used on Lists?

How Do Python\'s `append()` and ` =` Operators Differ When Used on Lists?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-31 12:24:46583browse

How Do Python's `append()` and ` =` Operators Differ When Used on Lists?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn