Python: deepcopy(list) vs new_list = old_list[:]

Python: deepcopy(list) vs new_list = old_list[:],第1张

Python: deepcopy(list) vs new_list = old_list[:]

You asked two questions:

Deep vs. shallow copy

matrix[:]
is a shallow copy -- it only copies the elements directly
stored in it, and doesn’t recursively duplicate the elements of arrays or
other references within itself. That means:

a = [[4]]b = a[:]a[0].append(5)print b[0] # Outputs [4, 5], as a[0] and b[0] point to the same array

The same would happen if you stored an object in

a
.

deepcopy()
is, naturally, a deep copy -- it makes copies of each of its
elements recursively, all the way down the tree:

a = [[4]]c = copy.deepcopy(a)a[0].append(5)print c[0] # Outputs [4], as c[0] is a copy of the elements of a[0] into a new array
Returning

return final.append(li)
is different from calling
append
and returning
final
because list.append does not return the list object itself, it returns
None



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5663782.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存