Table of Contents
Object copy" >Object copy
Home Backend Development Python Tutorial Understanding Python assignment and copying

Understanding Python assignment and copying

Apr 19, 2018 pm 03:24 PM
python copy Assignment

The examples in this article describe understanding Python assignment and copying. Share it with everyone for your reference, the details are as follows:

Variables and Assignment

In Python, everything is an object, and objects pass through "variables" "name" reference, "variable name" is more accurately called "name", just like each of us has his own name, we refer to a person by name, and an object is referred to by name in the code.

Variable assignment is to bind a name to the object. Assignment does not copy the object. Just like our parents give us a name when we are born, giving someone a nickname does not create an extra person, it just creates an extra name.

There are two ways to compare two objects, namely: is and ==, is What is compared is whether the two objects are the same. Whether they are the same can be identified by the ID value of the object. Object, == compares whether the values ​​​​of the two objects are equal

<code class="hljs python" style="font-size:.85em;font-family:Consolas, Inconsolata, Courier, monospace;margin:0px .15em;white-space:pre;border-width:1px;border-style:solid;border-color:rgb(204,204,204);padding:.5em;color:rgb(51,51,51);background:rgb(248,248,248);"><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x1 = [<span class="hljs-number" style="color:rgb(0,128,128);">1</span>,<span class="hljs-number" style="color:rgb(0,128,128);">2</span>]<br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x2 = [<span class="hljs-number" style="color:rgb(0,128,128);">1</span>,<span class="hljs-number" style="color:rgb(0,128,128);">2</span>]<br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x1 <span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">is</span> x2<br><span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">False</span><br><br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>id(x1)<br><span class="hljs-number" style="color:rgb(0,128,128);">4338854088</span><br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>id(x2)<br><span class="hljs-number" style="color:rgb(0,128,128);">4338904392</span><br><br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x1 == x2<br><span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">True</span></code>
Copy after login

Although the values ​​​​of x1 and x2 are the same, they are two independent and different objects in the memory, occupying different The memory space is like two identical apples placed on the table, but they are actually two different objects.

<code class="hljs python" style="font-size:.85em;font-family:Consolas, Inconsolata, Courier, monospace;margin:0px .15em;white-space:pre;border-width:1px;border-style:solid;border-color:rgb(204,204,204);padding:.5em;color:rgb(51,51,51);background:rgb(248,248,248);"><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x3 = x2<br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x3 <span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">is</span> x2<br><span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">True</span><br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>id(x3)<br><span class="hljs-number" style="color:rgb(0,128,128);">4338904392</span></code>
Copy after login

As mentioned before, assignment is to bind a name to an object. Here we just bind a new name to the object corresponding to x2 called x3. This is like putting an apple on the table. At first it was labeled x2, and later it was labeled x3. It is essentially the same apple, so x2 and x3 actually refer to the same object.

Understanding Python assignment and copying

When the object is modified through x2, x3 will also change because they are essentially the same object. This is like when Zhang San and Xiao Zhang are the same person, Adding clothes to Zhang San is actually adding clothes to Xiao Zhang.

<code class="hljs python" style="font-size:.85em;font-family:Consolas, Inconsolata, Courier, monospace;margin:0px .15em;white-space:pre;border-width:1px;border-style:solid;border-color:rgb(204,204,204);padding:.5em;color:rgb(51,51,51);background:rgb(248,248,248);"><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x2.append(<span class="hljs-number" style="color:rgb(0,128,128);">3</span>)<br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x2<br>[<span class="hljs-number" style="color:rgb(0,128,128);">1</span>, <span class="hljs-number" style="color:rgb(0,128,128);">2</span>, <span class="hljs-number" style="color:rgb(0,128,128);">3</span>]<br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x3<br>[<span class="hljs-number" style="color:rgb(0,128,128);">1</span>, <span class="hljs-number" style="color:rgb(0,128,128);">2</span>, <span class="hljs-number" style="color:rgb(0,128,128);">3</span>]</code>
Copy after login

However, when I reassign x2, it means that x2 no longer refers to the previous object, but refers to the new object, and x3 still refers to the previous object. For example, a big apple on the table has two labels: x2 and x3. Reassigning a value to x2 is equivalent to attaching the x2 label to another apple, but x3 is still attached to the old apple.

<code class="hljs python" style="font-size:.85em;font-family:Consolas, Inconsolata, Courier, monospace;margin:0px .15em;white-space:pre;border-width:1px;border-style:solid;border-color:rgb(204,204,204);padding:.5em;color:rgb(51,51,51);background:rgb(248,248,248);"><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x2 = [<span class="hljs-number" style="color:rgb(0,128,128);">3</span>, <span class="hljs-number" style="color:rgb(0,128,128);">4</span>]<br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x3<br>[<span class="hljs-number" style="color:rgb(0,128,128);">1</span>, <span class="hljs-number" style="color:rgb(0,128,128);">2</span>, <span class="hljs-number" style="color:rgb(0,128,128);">3</span>]</code>
Copy after login

Understanding Python assignment and copying

Object copy

Sometimes in business we need to copy an object, but we don’t want to have side effects on the original object, definitely It cannot be solved by assigning a value to a new variable (because assignment is not a copy of the object), so Python specifically provides a copy mechanism to quickly create an object with the same value based on the original object. This functionality is provided by the copy module.


Copy is divided into shallow copy and deep copy.

>>> s = [1,2,3]
>>> sc = copy.copy(s) # 浅拷贝
>>> sc
[1, 2, 3]
Copy after login
<code class="hljs python" style="font-size:.85em;font-family:Consolas, Inconsolata, Courier, monospace;margin:0px .15em;white-space:pre;border-width:1px;border-style:solid;border-color:rgb(204,204,204);padding:.5em;color:rgb(51,51,51);background:rgb(248,248,248);"><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>sdc = copy.deepcopy(s)  <span class="hljs-comment" style="color:rgb(153,153,136);font-style:italic;"># 深拷贝</span><br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>sdc<br>[<span class="hljs-number" style="color:rgb(0,128,128);">1</span>, <span class="hljs-number" style="color:rgb(0,128,128);">2</span>, <span class="hljs-number" style="color:rgb(0,128,128);">3</span>]</code>
Copy after login

The copied objects only have the same value, but are actually different objects

<code class="hljs python" style="font-size:.85em;font-family:Consolas, Inconsolata, Courier, monospace;margin:0px .15em;white-space:pre;border-width:1px;border-style:solid;border-color:rgb(204,204,204);padding:.5em;color:rgb(51,51,51);background:rgb(248,248,248);"><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>s == sc == sdc <br><span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">True</span><br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>s <span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">is</span> sc <br><span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">False</span><br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>s <span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">is</span> sdc<br><span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">False</span></code>
Copy after login

So what is the difference between shallow copy and deep copy?

For immutable objects, such as integers, strings, tuples, and collection objects composed of these immutable objects, there is no difference between shallow copy and deep copy, both copy a new object

两者的区别在于拷贝组合对象,比如列表中还有列表,字典中还有字典或者列表的情况时,浅拷贝只拷贝了外面的壳子,里面的元素并没有拷贝,而深拷贝则是把壳子和里面的元素都拷贝了一份新的。

来看一个例子:

<code class="hljs python" style="font-size:.85em;font-family:Consolas, Inconsolata, Courier, monospace;margin:0px .15em;white-space:pre;border-width:1px;border-style:solid;border-color:rgb(204,204,204);padding:.5em;color:rgb(51,51,51);background:rgb(248,248,248);"><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>x = [<span class="hljs-number" style="color:rgb(0,128,128);">2</span>, <span class="hljs-number" style="color:rgb(0,128,128);">3</span>]<br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>y = [<span class="hljs-number" style="color:rgb(0,128,128);">7</span>, <span class="hljs-number" style="color:rgb(0,128,128);">11</span>]<br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>z = [x, y]<br><br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>a = copy.copy(z) <span class="hljs-comment" style="color:rgb(153,153,136);font-style:italic;"># 浅拷贝</span><br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>a[<span class="hljs-number" style="color:rgb(0,128,128);">0</span>] <span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">is</span> z[<span class="hljs-number" style="color:rgb(0,128,128);">0</span>]<br><span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">True</span></code>
Copy after login

Understanding Python assignment and copying

拷贝出来的对象 a 中的元素引用的是 x 和 y,当你修改 x 的值,a 也会跟着变。

<code class="hljs python" style="font-size:.85em;font-family:Consolas, Inconsolata, Courier, monospace;margin:0px .15em;white-space:pre;border-width:1px;border-style:solid;border-color:rgb(204,204,204);padding:.5em;color:rgb(51,51,51);background:rgb(248,248,248);text-align:justify;"><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>b = copy.deepcopy(z) <span class="hljs-comment" style="color:rgb(153,153,136);font-style:italic;"># 深拷贝</span><br><span class="hljs-prompt" style="color:rgb(153,0,115);">>>> </span>b[<span class="hljs-number" style="color:rgb(0,128,128);">0</span>] <span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">is</span> z[<span class="hljs-number" style="color:rgb(0,128,128);">0</span>]<br><span class="hljs-keyword" style="color:rgb(51,51,51);font-weight:bold;">False</span></code>
Copy after login

Understanding Python assignment and copying

对于深拷贝,里面的元素也重新拷贝了一份,拷贝了一份与x和y等值的两个元素,修改 x 和 y 的值,不会对 b 产生影响


对列表的切片拷贝 z[:] 或者是调用对象的copy方法 list.copy() 都属于浅拷贝。对于自定义对象,我们还可以自己实现 __copy__方法和 __deepcopy__方法


相关阅读:

Django入门实践指南-第1部分
厉害了,10行代码实现抽奖助手自动参与抽奖
看了很多代码,却依然无从下手?

The above is the detailed content of Understanding Python assignment and copying. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

See all articles