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

Source: Internet
Author: User
Tags shallow copy
In this article we will learn about the Python dictionary python copy functionThe relevant knowledge, python copyWhat it means is that what he does will be answered in the next article.

Summary description

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

Grammar

Copy () method syntax:

Dict.copy ()

Parameters

NA.

return value

Returns a shallow copy of a dictionary.

Instance

The following example shows how the copy () function is used:

#!/usr/bin/pythondict1 = {' Name ': ' Zara ', ' Age ': 7};d Ict2 = Dict1.copy () print "New dictinary:%s"% str (DICT2)

The result of the above example output is:

New dictinary: {' age ': 7, ' Name ': ' Zara '}

The difference between direct assignment and copy

This can be illustrated by the following examples:

#!/usr/bin/python#-*-Coding:utf-8-*-dict1 = {' user ': ' runoob ', ' num ': [1, 2, 3]}dict2 = dict1  # Shallow copy: Reference object DICT3 = Dict1.copy ()  # Shallow copy: Deep copy Parent object (First level directory), sub-object (level two directory) not copy, or reference # Modify data dict1[' user '] = ' root ' dict1[' num '].remove (1) # Output print (dict1) print (dict2) print (DICT3)

The dict2 in the instance is actually a reference (alias) of the Dict1, so the output is consistent, dict3 the parent object is deeply copied, does not change with the Dict1 modification, the sub-object is a shallow copy, so modify with the Dict1.

{' num ': [2, 3], ' user ': ' Root '} {' num ': [2, 3], ' user ': ' Root '} {' num ': [2, 3], ' user ': ' Runoob '}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.