Copy a list in Python
This post will discuss how to copy a list in Python.
This article explores different ways to perform generic shallow copy operation in Python. A shallow copy means that if the elements of the original list are mutable objects themselves (such as other lists), modifying them will also affect the copied list.
1. Using copy() function
The standard solution to return a shallow copy of the list is with the built-in copy() function. This function is available for lists, sets, and dictionaries.
|
1 2 3 4 |
ints = [1, 2, 3, 4, 5] copy = ints.copy() print(copy) # [1, 2, 3, 4, 5] |
2. Using slicing technique
Another preferred fast way to create a shallow copy of a list is to use the slicing technique [:]. This will create a new list object that contains all the elements of the original list. A slice of the entire list l[:] is essentially the same as doing l.copy().
|
1 2 3 4 |
ints = [1, 2, 3, 4, 5] copy = ints[:] print(copy) # [1, 2, 3, 4, 5] |
3. Using List Constructor
You can also copy a list by using the list() constructor function. This will create a new list object from an iterable object (such as another list). For example:
|
1 2 3 4 |
ints = [1, 2, 3, 4, 5] copy = list(ints) print(copy) # [1, 2, 3, 4, 5] |
4. Using copy.copy() function
Another way to copy a Python list is to use the copy.copy() function from the copy module. The copy module provides routines for shallow and deep copy operations. The copy.copy() function will create a new list object that is a shallow copy of the original list. If you want to create a deep copy of the original list, use the copy.deepcopy() function instead. For example:
|
1 2 3 4 5 6 |
from copy import copy ints = [1, 2, 3, 4, 5] copy = copy(ints) print(copy) # [1, 2, 3, 4, 5] |
5. Using extend() function
Finally, you can use the extend() function to copy a list. The x.extend(y) function or x += y syntax extends the list x with the contents of y. Following is a simple example demonstrating this:
|
1 2 3 4 5 6 |
ints = [1, 2, 3, 4, 5] copy = [] copy.extend(ints) print(copy) # [1, 2, 3, 4, 5] |
That’s all about copying a list in Python. Please refer to this post for performing a deep copy of a list.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)