Sometimes, there is a need to reuse any object, hence copy methods are always of a great utility. Python in its language offers a number of ways to achieve this. This particular article aims at demonstrating the copy method present in list. Since list is widely used hence, its copy is also necessary.
Syntax : list.copy()
Returns a shallow copy of a list.
Shallow copy means the any modification in new list won’t be reflected to original list
Code #1 : Demonstrating the working of list.copy()
The new list created is : [1, 2, 3, 4] The new list after adding new element : [1, 2, 3, 4, 5] The old list after adding new element to new list : [1, 2, 3, 4]
Deep Copy vs Shallow copy : An Analysis
Deep copy means if we modify any of the list, changes are reflected in both the list as they point to the same reference. Whereas in shallow copy, when we add element in any of the list, only that list is modified.
Techniques to deep copy :
- Using copy.deepcopy()
- Using “=” operator
Techniques to shallow copy :
- Using copy.copy()
- Using list.copy()
- Using slicing
Code #2 : Demonstrating techniques of shallow and deep copy
The new list created using copy.copy() : [1, 2, 3, 4, 5] The new list created using list.copy() : [1, 2, 3, 4, 5] The new list created using slicing : [1, 2, 3, 4, 5] The old list after adding new element to new list : [1, 2, 3, 4] The new list created using copy.deepcopy() : [1, 2, 3, 4, 5] The new list created using = : [1, 2, 3, 4, 5] The old list after adding new element to new list : [1, 2, 3, 4, 5]
- Python | How to copy a nested list
- copy in Python (Deep Copy and Shallow Copy)
- Python PIL | copy() method
- Python | shutil.copy() method
- set copy() in python
- Python Dictionary copy()
- Python | Pandas Index.copy()
- Python | Pandas TimedeltaIndex.copy
- Python | Ways to Copy Dictionary
- Python | Numpy matrix.copy()
- numpy.ndarray.copy() in Python
- Python Number | cmp(list) method
- Python | Move or Copy Files and Directories
- Python | How to copy data from one excel sheet to another
- Copy a directory recursively using Python (with examples)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.