Home  >  Article  >  Backend Development  >  What is the copy function? What is the difference between direct assignment and copy?

What is the copy function? What is the difference between direct assignment and copy?

乌拉乌拉~
乌拉乌拉~Original
2018-08-18 17:55:088342browse

In this article, let’s learn about the python copy function in the python dictionary. What does python copy mean? What functions does it have? Get the answer in the article below.

Summary description

Python Dictionary copy() function returns a shallow copy of the dictionary.

Syntax

copy() method syntax:

dict.copy()

Parameters

##NA.

Return value

Returns a shallow copy of the dictionary.

Example

The following example shows how to use the copy() function:

# !/usr/bin/python

dict1 = {'Name': 'Zara', 'Age': 7};

dict2 = dict1.copy()
print "New Dictinary : %s" % str(dict2)

The output result of the above example is:

New Dictinary : {'Age': 7, 'Name': 'Zara'}

The difference between direct assignment and copy

can be explained through the following examples:

# !/usr/bin/python
# -*- coding: UTF-8 -*-

dict1 = {'user': 'runoob', 'num': [1, 2, 3]}

dict2 = dict1  # 浅拷贝: 引用对象
dict3 = dict1.copy()  # 浅拷贝:深拷贝父对象(一级目录),子对象(二级目录)不拷贝,还是引用

# 修改 data 数据
dict1['user'] = 'root'
dict1['num'].remove(1)

# 输出结果
print(dict1)
print(dict2)
print(dict3)

In the example, dict2 is actually a reference (alias) of dict1, so the output result They are all consistent. The parent object of dict3 is deeply copied and will not be modified when dict1 is modified. The child object is a shallow copy, so it is modified when dict1 is modified.

{'num': [2, 3], 'user': 'root'}
{'num': [2, 3], 'user': 'root'}
{'num': [2, 3], 'user': 'runoob'}

The above is all the content of this article, the built-in copy function of the dictionary in Python. I hope what I said and the examples I gave can be helpful to you.

For more related knowledge, please visit the

Python tutorial column on the php Chinese website.

The above is the detailed content of What is the copy function? What is the difference between direct assignment and copy?. 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