In Python, we use = operator to create a copy of an object. You may think that this creates a new object; it doesn’t. It only creates a new variable that shares the reference of the original object. Let’s take an example where we create a list named old_list and pass an object reference to new_list using = operator.
What does copy () do in Python?
The Python copy() method creates a copy of an existing list. The copy() method is added to the end of a list object and so it does not accept any parameters. copy() returns a new list. Python includes a built-in function to support creating a shallow copy of a list: copy().
How do you copy a list?
- You can use the builtin list.copy() method (available since Python 3.3): new_list = old_list.copy()
- You can slice it: new_list = old_list[:] …
- You can use the built in list() function: new_list = list(old_list)