Home > Backend Development > Python Tutorial > How to Create Python Lists by Value, Not by Reference?

How to Create Python Lists by Value, Not by Reference?

DDD
Release: 2025-01-02 15:36:10
Original
362 people have browsed it

How to Create Python Lists by Value, Not by Reference?

Creating Python Lists by Value, Not Reference

In Python, variables referring to lists actually reference the list objects themselves. This means that modifications made to one list affect all variables referencing that list.

Consider the following example:

a = ['help', 'copyright', 'credits', 'license']
b = a
b.append('XYZ')

print(b)
# ['help', 'copyright', 'credits', 'license', 'XYZ']

print(a)
# ['help', 'copyright', 'credits', 'license', 'XYZ']
Copy after login

As you can see, appending a value to b also affects a because both variables point to the same list object in memory.

To create a copy of a list, you can use the slicing operator ([:]):

b = a[:]

b.append('XYZ')

print(b)
# ['help', 'copyright', 'credits', 'license', 'XYZ']

print(a)
# ['help', 'copyright', 'credits', 'license']
Copy after login

In this case, b and a are now pointing to separate list objects, so modifying one does not affect the other.

The above is the detailed content of How to Create Python Lists by Value, Not by Reference?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template