make a copy of list in python
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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具