copy() – copy list

The most direct way to copy a list in Python is via the copy() method.

Code Example

  1. The first line of the code creates a list named sourceList and assigns it the values [1, 2, 3, 4, 5].
  2. The second line of the code creates a new list named 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.
  3. The 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.
  4. The 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.
  5. The loop continues until all elements in 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=" ")
Output
1 2 3 4 5