copy() method to get a copy of a list

copy() takes no arguments .

Returns a copy of the main list.
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']

Example 2: Shallow vs Deep Copy of Nested Lists

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]
  • This shows that shallow copy cannot isolate changes in nested lists, while deep copy does.

Example 3: Copying Large Lists Efficiently


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)
  • Compares performance of list.copy() vs slicing for large lists.
  • Good for readers who plan to use copying in data‑heavy situations.

Example 4: Copying Custom Objects Implementing __copy__


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)
  • Illustrates when list subclass overrides the behavior of copy.

Edge Cases & Best Practices

  • What happens when list has mutable items (nested lists, dicts)? Use deep copy for full independence.
  • Copying empty list returns a new empty list.
  • Changing the original list does not affect a list made via copy() for top‑level elements.
  • Good to mention memory cost when copying very large lists.
All list methods Questions with solutions on List
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer