Python's copy and assignment of the interview topic

Source: Internet
Author: User
Tags shallow copy

Python uses the structure of reference variables, it is said that if you assign a value to a variable, it does not give the variable a piece of memory space, but the memory of an object to tell the address of the variable, the benefits of this is easy to manage, save memory space, easy memory release and so on. In some special cases, however, a variable with its own memory space is required, so that it does not interfere with the original variable. That will use the copy of the object.

Next look at how the variables are copied:

Demand:

You want to copy an object. Because in Python, whether you pass an object as a parameter, as a function return value, it is passed by reference.

Discuss:

The copy module in the standard library provides two methods for copying. A method is copy, which returns an object that contains the same contents as the argument.

Import Copy
New_list = Copy.copy (existing_list)

There are times when you want properties in an object to be copied, you can use the Deepcopy method:

Import Copy
New_list_of_dicts = Copy.deepcopy (existing_list_of_dicts)

When you assign a value to an object (either as a parameter or as a return value), Python, like Java, always passes a reference to the original object, not a copy. Other languages always pass a copy when assigning values. Python never guesses the user's needs if you want a copy , you must explicitly ask for it. The behavior of
Python is simple, fast, and consistent. However, if you need an object copy and do not explicitly write it out, there will be problems, such as:
>>> a = [1 , 2, 3]
>>> b = a
>>> b.append (5)
>>> print A, b
[1, 2, 3, 5] [1, 2, 3, 5]
Here, the variables A and b all point to the same object (a list), so once you modify one of the two, the other one will be affected. In any case, the original object will be modified .
Note:
to be a Python master, the first thing to note is the object's change operation and assignment, which are all references to the object. A statement such as a = [] binds a to a new object, but does not affect the previous object. However, object replication is different, When an object is copied, the object change operation is different.
If you want to modify an object and you want the original object to be unaffected, you need to copy the object. As this section says, you can use the two methods in the copy module to implement the requirements. In general, you can use Copy.copy, which can be used to make shallow copies of objects (shallow copy), which copies the object, but still uses the reference for the element in the object.
Shallow copy, sometimes unable to get a copy identical to the original object, if you want to modify the object in the element, not just the object itself:

>>> list_of_lists = [[' A '], [1, 2], [' Z ', +]]
>>> copy_lol = copy . Copy (lists_of_lists)
>>> copy_lol[1].append (' Boo ')
>>> print list_of_lists, copy_lol
[[' A '], [1, 2, ' Boo '], [' Z ', [+]] [[' A '], [1, 2, ' Boo '], [' Z ',]]

Here, the variable list_of_lists,copy_lol points to two different objects, so we can modify any one of them without affecting the other. However, if we modify the elements in one object, then the other is affected because the elements in them are still shared references.
If you want to copy a container object, and all of its elements (containing the element's child elements), using Copy.deepcopy, this method consumes some time and space, but if you need to replicate completely, this is the only way.
For a general shallow copy, use Copy.copy, of course, you need to know the object you want to copy. To copy the list L, using list (L), to copy a dictionary d, using Dict (d), to copy a set S, using Set (s), so that we summarize a rule, If you want to copy an object o, which belongs to the built-in type T, then you can use T (o) to get a copy. Dict also provides a copy of the version, Dict.copy, this and dict (d) is the same, I recommend you use the latter, this makes the code more consistent, but also a few characters.
To copy a different type, whether you write your own or use the library, use Copy.copy, if you write a class yourself, there is no need to bother to write clone and copy functions, if you want to define your own way of copying the class, implement a __copy__, or __getstate __ and __setstate__. If you want to define your own type of deepcopy, implement the method __deepcopy__.
Note that you don't have to copy non-modifiable objects (strings, numbers, tuples) because you don't have to worry about modifying them. If you want to try replication, you will still get the original. It's harmless, but it's a waste of effort:

>>> s = ' cat '
>>> T = copy.copy (s)
>>> S is t
True

The IS operator is used to not only determine whether two objects are exactly the same, but is the same object (is judgment identifier, to compare content, use = =), it is not meaningful to judge whether an identifier is equal to a non-modifiable object. However, it is sometimes important to judge identifiers for modifiable objects, for example, You are not sure whether a and B point to the same object, and A is B will get the result immediately. This allows you to decide for yourself whether to use object copies.
Attention:
You can use a different copy method, given a list L, whether it is a full slice l[:] or list parsing [x for x in L], will get a shallow copy of L, try l+[],l*1 ... but the above two methods will be confusing, using list (L) clearest and fast, of course, For historical reasons, you may often see the l[:] notation.
For Dict, you may have seen the following replication methods:
>>> for Somekey in D:
... d1[somekey] = D[somekey]

Or simpler methods, D1={},d1.update (d), anyway, the code is inefficient, use D1=dict (d).

Related instructions:

Copy (x)
Shallow copy operation on arbitrary Python objects.

See the module ' s __doc__ string for more info.

Deepcopy (x, Memo=none, _nil=[])
Deep copy operation on arbitrary Python objects.

See the module ' s __doc__ string for more info.

Reference

Python's copy and assignment of the interview topic

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.