The most direct way to copy a list in Python is via the copy()
method.
sourceList
and assigns it the values [1, 2, 3, 4, 5]
.targetList
and assigns it the value of sourceList.copy()
. The copy
method is used to create a shallow copy of the sourceList
object. This means that a new list is created with the same elements as sourceList
, but the new list and the original list are two separate objects in memory, and changes to one will not affect the other.for
loop in the code iterates over the elements of the list targetList
. For each iteration, the current element is stored in the variable i
.print
function is used to print the current value of i
during each iteration of the loop. The end
parameter is set to a space character, so that the numbers are printed on the same line with a space between each number.targetList
have been processed.So, the code creates a source list, creates a copy of the source list, and then prints all the elements of the copy, separated by a space.
sourceList = [1, 2, 3, 4, 5]
targetList = sourceList.copy()
for i in targetList:
print(i, end=" ")
1 2 3 4 5