Home > Backend Development > Python Tutorial > Python Lists: Pass by Value or Reference?

Python Lists: Pass by Value or Reference?

Patricia Arquette
Release: 2024-11-27 18:34:12
Original
989 people have browsed it

Python Lists: Pass by Value or Reference?

List Manipulation in Python: Passing by Value vs. Reference

While working with lists in Python, one common challenge is the concept of passing by reference and understanding how it affects list changes. Let's explore a scenario to illustrate this issue:

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

In this example, you intend to append a value to list 'b,' but surprisingly, the value of list 'a' also changes. This is because, in Python, lists (and other objects) are passed by reference, which means they share the same memory location.

So, when you assign 'b' to 'a,' you're not creating a new list but referencing the same one. Therefore, any changes made to one list will be reflected in the other.

How to Pass by Value

To avoid unintended changes, you need to create a new list that's a copy of the original. In Python, slicing can be used to achieve this:

b = a[:]
Copy after login

By using the slice operator [:] on list 'a,' you create a new list 'b' that contains all elements of 'a' but occupies a separate memory location. Now, any changes made to 'b' will not affect 'a.'

The above is the detailed content of Python Lists: Pass by Value or 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template