chevron_left
Cookbooks
Accessing an item in a listAdding items to a listChecking if a list is emptyChecking whether a value is in a listConcatenating two listsCopying a list in PythonDifference between append and extend methodsDifference between sort and sortedFinding the index of an element in a listFinding the length of a listIterating from index oneLooping through listsModifying listsPrinting a list in reverse orderRemoving items from a listSorting a listUsing enumerate and zip at the same time
0
0
0
new
Copying a list in Python
Programming
chevron_rightPython
chevron_rightOperations
chevron_rightList Operations
chevron_rightCookbooks
schedule Jul 1, 2022
Last updated Python
Tags tocTable of Contents
expand_more There are two main ways to copy a list in Python:
Method copy
The list.copy
method can be leveraged to copy a list:
original_list = ['apples', 'bananas', 'pears', 'oranges']copy_list = original_list.copy()print(copy_list)
['apples', 'bananas', 'pears', 'oranges']
Slicing
We create a slice from the very start of original_list
to the very end (i.e. copying the entire list)
original_list = ['apples', 'bananas', 'pears', 'oranges']copy_list = original_list[:]print(copy_list)
['apples', 'bananas', 'pears', 'oranges']
Incorrect way to copy
original_list = ['apples','bananas','pears','oranges']copy_list = original_list
The above syntax will lead to copy_list
and original_list
both pointing to the same list. Therefore updating original_list
will also mean copy_list
is updated automatically which is something we do not want.
Published by Arthur Yanagisawa
Edited by 0 others
Did you find this page useful?
Ask a question or leave a feedback...
0
0
0
Enjoy our search