![]() ![]() However, we are going to create deep copy using deepcopy() function present in copy module. This is because, both lists share the reference of same nested objects.Ī deep copy creates a new object and recursively adds the copies of nested objects present in the original elements. Both sublists of old_list and new_list at index were modified. In the above program, we made changes to old_list i.e old_list = 'AA'. When we run the program, it will output: Old list:, , ] However, when you change any nested objects in old_list, the changes appear in new_list.Įxample 4: Adding new nested object using Shallow copy import copy This new sublist was not copied in new_list. Then we add the new list i.e into old_list. The new_list contains references to original nested objects stored in old_list. In the above program, we created a shallow copy of old_list. When we run the program, it will output: Old list:, ,, ] To confirm that new_list is different from old_list, we try to add new nested object to original and check it.Įxample 3: Adding to old_list, using shallow copy import copy To verify this, we print the both old_list and new_list. This means it will create new and independent object with same content. In above program, we created a nested list and then shallow copy it using copy() method. When we run the program, the output will be: Old list:, , ] Example 2: Create a copy using shallow copy import copy This means, a copy process does not recurse or create copies of nested objects itself. So, a shallow copy doesn't create a copy of nested objects, instead it just copies the reference of nested objects. Similarly, deepcopy() return a deep copy of x.Ī shallow copy creates a new object which stores the reference of the original elements. Here, the copy() return a shallow copy of x. Suppose, you need to copy the compound list say x. We use the copy module of Python for shallow and deep copy operations. To make these copy work, we use the copy module. In Python, there are two ways to create copies: So, if you want to modify any values in new_list or old_list, the change is visible in both.Įssentially, sometimes you may want to have the original values unchanged and only modify the new values or vice versa. New List:, , ]Īs you can see from the output both variables old_list and new_list shares the same id i.e 140673303268168. When we run above program, the output will be: Old List:, , ] Example 1: Copy using = operator old_list =, , ] Let's take an example where we create a list named old_list and pass an object reference to new_list using = operator. It only creates a new variable that shares the reference of the original object. You may think that this creates a new object it doesn't. In Python, we use = operator to create a copy of an object. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |