Copy List Using Slicing
Here we are copying the list using the list slicing method [:] and we are appending the ‘a’ to the new_list. After printing we can see the newly appended character ‘a’ is not appended to the old list.
Python3
list = [ 2 , 4 , 6 ] new_list = list [:] new_list.append( 'a' ) print ( 'Old List:' , list ) print ( 'New List:' , new_list) |
Old List: [2, 4, 6] New List: [2, 4, 6, 'a']
We discussed the definition, syntax and examples of list copy() method. copy() function is very useful when working with sensitive data and you can’t risk mistakes.
We also briefly talked about shallow vs deep copy. Hope this helped you in understanding copy() function in Python.
Read Other Python List Methods
More articles on to list copy:
Python List copy() Method
The list Copy() method makes a new shallow copy of a list.
Example
Python3
# Using list fruits fruits = [ "mango" , "apple" , "strawberry" ] # creating a copy shakes shakes = fruits.copy() # printing shakes list print (shakes) |
['mango', 'apple', 'strawberry']