Home >Backend Development >Python Tutorial >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!