Last Updated on June 17, 2021 by Roshan Parihar
In this tutorial, learn how to copy list elements to another variable using Python. The short answer is: use the copy()
to clone the list element to other list variables. You can create a clone of the list and get the list elements from the new variable.
You can also copy all the elements from one list to another. Check each example showing the method to copy the list elements. Learn each method one by one and execute the examples to get output.
Clone or Copy List Element to Other Using Python Copy()
If you want to copy the list to other Python variable. You have to use the Python copy()
. To use the function, you have to use the list variable followed by the function. Now, assign this to the list variable where you want to copy this list.
1 2 3 |
old_List = ["one", "two", 37, "four", 51]; newList = old_List.copy(); print(newList); |
Output
The above example prints the new list elements which are the exact copy of the old list. It copied all the elements of the first list to the second list.
You can also assign one list element to the other list element. To perform this task using Python, you have to read further.
Assign One List to Other For Cloning in Python
You can also assign one list element to the other variable in Python. To perform this task, you have to equate the old list to the new list. This clone the old list elements to the new list elements.
This works the same as the above-given example but it assigns the list to a new variable.
1 2 3 |
old_List = ["one", "two", 37, "four", 51]; newList = old_List; print(newList); |
Output
The above example showing the list elements of the new list variable. Check the above example assigning the old variable to the new variable. It prints the output using the Python print statement.
Copy Elements of One List to Other Using Python Extend()
In addition to above all, you can also add the elements of one list to the other list. To perform this task, you have to use the Python extend()
and pass the list variable as the argument.
Use the below-given example to extend one list to the other list. You may also like to read how to append or insert elements to list in Python
1 2 3 4 |
old_List1 = ["one", "two", 37, "four", 51]; old_List2 = ["third", "forth", 21]; old_List1.extend(old_List2); print(old_List1); |
Output
The above example showing the list elements after the addition. You can say that this list is the copied list of the others including old elements. This is the combined elements of the two list in Python.
DOWNLOAD Free PYTHON CHEAT SHEET
You may also like to read
- Find the index of a given element of list Using Python
- How to change or reverse list element using Python
- Get list element by index in Python
- how to check if the list is empty or not using Python
I hope you like this tutorial on how to copy one list to the other using Python.
References