my_list=['Alex','Ronald','John','Ronald','Ronn']
my_list2=my_list.copy()
print(my_list2)
Output
['Alex', 'Ronald', 'John', 'Ronald', 'Ronn']
We can create a copy by selecting all the elements.
my_list=['Alex','Ronald','John','Ronald','Ronn']
my_list2=my_list[:]
print(my_list2)
Output
['Alex', 'Ronald', 'John', 'Ronald', 'Ronn']
import copy
original = [1, [2, 3], 4]
shallow = original.copy()
deep = copy.deepcopy(original)
original[1][0] = 'X'
print("Shallow:", shallow) # ['1', ['X', 3], 4]
print("Deep:", deep) # [1, [2, 3], 4]
import time
big = list(range(1000000))
start = time.time()
big_copy = big.copy()
print("copy() took:", time.time() - start)
start2 = time.time()
slice_copy = big[:]
print("slice took:", time.time() - start2)
class MyList(list):
def __copy__(self):
print("Using custom copy")
return MyList(self[:])
orig = MyList([10, 20, 30])
c = orig.copy()
print(type(c), c)
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.