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

Mary-Kate Olsen
Release: 2024-10-31 12:24:46
Original
588 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!