In this article, we will learn to copy lists in a python program. There are so many different ways to copy a list in python.
Method 1: Using the Slicing Technique
The simplest way to clone or copy a list is to use the slice method. This method creates a new list that contains all the elements of the original list. Here's how you can use it:
Explanation
- First, we will initialize the list1.
- Then we will store all the elements of list1 to list1 using the slicing method.
- Then we will print the original list1 and list2.
Program
1
2
3
4
5
6
7
8
9 | # initialize the list1
list1 = [1, 2, 3, 4, 5, 6]
# copying to list2 using sclicing method
list2 = list1[:]
# print the result
print("Original List:", list1)
print("After Copying:", list2)
|
Output
Original List: [1, 2, 3, 4, 5, 6]
After Copying: [1, 2, 3, 4, 5, 6]
Method 2: Using extend() methods
The list elements copy to the new list using extend() function in python. Here's how you can use it.
Explanation
- First, we will initialize list1 and list2.
- list2 is empty.
- Then we will use extend() function to appends all the elements to list2.
- Then, we will print the result.
Program
1
2
3
4
5
6
7
8
9
10
11
12 | # initialize the list1
list1 = [1, 2, 3, 4, 5, 6]
# initialize the list2
list2 = []
# copying to list2 using extend() function
list2.extend(list1)
# print the result
print("Original List:", list1)
print("After Copying:", list2)
|
Output
Original List: [1, 2, 3, 4, 5, 6]
After Copying: [1, 2, 3, 4, 5, 6]
Method 3: Using (=)Assignment Operator
This is the easiest or simple method to copy the list in python. We will use the assignment operator to copy the list in python.
Explanation
- First, we will initialize the list1.
- Copy the list1 to list2 using the assignment operator(=).
- Then, print the result.
Program
1
2
3
4
5
6
7
8
9 | # initialize the list1
list1 = [1, 2, 3, 4, 5, 6]
# copy the list1 to list2 using assigment operators
list2 = list1
# print the result
print("Original List:", list1)
print("After Copying:", list2)
|
Output
Original List: [1, 2, 3, 4, 5, 6]
After Copying: [1, 2, 3, 4, 5, 6]
Conclusion
In this article, we learned, how to copy or cloning a list in python using different methods and techniques. All the methods is right and we can use according to our function.