make a copy of list in python

本文介绍了在Python中复制列表的不同方法及其区别,特别是针对一维和二维列表的复制,并强调了深拷贝在处理复杂数据结构时的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Methods to copy a list in python

As s freshman using python, It’s easy to be confused when copying a list. Here are some methods to make copy from originalList to targetList which are from the blog page, [Python]列表复制的几种方法. they are:

# python code
# No.1 DON'T USE THIS.
targetList = originalList # DON'T USE THIS, IT MAKES A CLONE NOT A COPY.
# No.2
targetList = originalList[:]
# No.3
targetList = list(originalList)
# No.4
targetList = originalList*1
# No.5
import copy
targetList = copy.copy(originalList)
# No.6
import copy
targetList = copy.deepcopy(originalList)

The perplexing point

When copying a list, one or more element of which is list, attentions should be payed to. In this case, the first 5 methods mentioned previously would not work as you want, only the 6th method mentioned previously could work exactly as you want.

Explain copying 2-dimensional list

by applying method No.1 targetList = originalList, one made a clone of the list originalList. the two variables share the same RAM units. One changes targetList[2], one changes originalList[2]. One changes originalList[2], one changes targetList[2]. It just like pointer in C language. targetList is the list name and targetList is the pointer name.
by applying method No.2~No.5, each element of targetList stored in a different RAM unit from elements of originalList. But, the content of the RAM units may be same. Saying, the two lists are physically different in 1st level, storing the same infomation. If the element is a number, it’s ok. If the element is another list, the element of targetList and its originalList counterpart have the same content, pointing to the same list(sublist). If one modified the content of the sublist, as the sublist is the sublist of both lists, both lists changed.

Still perplexing?

Here is a simple method getting things done. You just need:

import copy
targetList = copy.deepcopy(originalList)

then, everything is done.

references

  1. http://blog.youkuaiyun.com/flyapy/article/details/38041921
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值