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
DDDOriginal
2025-01-02 15:36:10357browse

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']

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']

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!

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