官术网_书友最值得收藏!

Copying lists

We have seen that Python variables are nothing but references to actual objects. The same holds true for lists. For this reason, manipulating lists gets a little tricky. By default, if we copy one list variable to another one by simply using the = operator, it won't actually create a duplicate or local copy of the list for that variable – instead, it would just create another reference and point the newly created reference toward the same memory location. Thus, when we make a change to the copied variable, the same change will be reflected in the original list. In the following example, we will create new isolated copies, where a change in the copied variable will not be reflected in the original list:

Now, let's look at how can we create a new copy of an existing list so that the changes to the new one do not cause any changes to the existing one:

Another way to create the isolated copy of the original list is to make use of the copy and deepcopy functions that are available in Python. A shallow copy constructs a new object and then inserts references to that object to the objects found in the original list. A deep copy, on the other hand, constructs a new compound object and then recursively inserts copies of the objects found in the original list:

主站蜘蛛池模板: 图木舒克市| 海门市| 夏津县| 兴安县| 徐水县| 二连浩特市| 霍林郭勒市| 鸡东县| 江永县| 政和县| 抚州市| 乌审旗| 河北区| 娄底市| 湘潭县| 荣昌县| 汉寿县| 鄂伦春自治旗| 奈曼旗| 天祝| 基隆市| 巴彦淖尔市| 昌乐县| 闽侯县| 白沙| 毕节市| 隆化县| 光山县| 临安市| 陆丰市| 通道| 分宜县| 南丹县| 左云县| 平利县| 胶南市| 台东市| 宜阳县| 玉门市| 苏尼特右旗| 乐至县|