.copy in python code example

Example 1: example of a deep copy in python

# deep copy example in python
import copy

old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.deepcopy(old_list)

old_list[1][0] = 'BB'

print("Old list:", old_list)
print("New list:", new_list)

# OUTPUT
Old list: [[1, 1, 1], ['BB', 2, 2], [3, 3, 3]]
New list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]

Example 2: python copy list

# Performance analysis by River on Stack Overflow
METHOD                  TIME TAKEN
b = [*a]                2.75180600000021
b = a * 1               3.50215399999990
b = a[:]                3.78278899999986  # Python2 winner
b = a.copy()            4.20556500000020
b = []; b.extend(a)     4.68069800000012
b = a[0:len(a)]         6.84498999999959
*b, = a                 7.54031799999984
b = list(a)             7.75815899999997
b = [i for i in a]      18.4886440000000
b = copy.copy(a)        18.8254879999999  # With `import copy`
b = []
for item in a:
    b.append(item)      35.4729199999997
  
# NOTE: Only for shallow copies, use copy.deepcopy for nested lists

Example 3: .copy python

new_list = list.copy()

# returns a new list without modifying the orginal list.

Example 4: python copy list

a=[1,2,3,4]
b=a[:] 
''' now b has all elements of  a'''