EN
Python - copy list
0 points
In this article, we would like to show you how to copy list in Python.
Quick solution:
xxxxxxxxxx
1
my_list = ['A', 'B', 'C']
2
3
list_copy = my_list.copy()
4
5
print(list_copy) # ['A', 'B', 'C']
In this example, we use copy()
method to create a copy of my_list
.
xxxxxxxxxx
1
my_list = ['A', 'B', 'C']
2
3
list_copy = my_list.copy()
4
5
print(list_copy) # ['A', 'B', 'C']
Output:
xxxxxxxxxx
1
['A', 'B', 'C']
Note:
You can't copy the list by simply using
list2 = list1
becauselist2
will only be a reference tolist1
.
In this example, we use list()
constructor to create a copy of my_list
.
xxxxxxxxxx
1
my_list = ['A', 'B', 'C']
2
3
list_copy = list(my_list)
4
5
print(list_copy) # ['A', 'B', 'C']
Output:
xxxxxxxxxx
1
['A', 'B', 'C']