OKPEDIA PYTHON LISTA EN

How to copy a list in Python

To copy a variable list in Python, you can use the slicing technique.

namelist2 = namelist[:]

The two points in square brackets [:] select all the elements of the list variable namelist.

How to copy a part of the list

To copy only a part of the list, you can indicate the first element of the partial list to the left of the two points (start) and the last element on the right (end).

namelist2 = namelist[start:end]

If the last element is indicated, the latter is not included in the copy list.

Note. If you don't specify the last element ( e.g. [1:] ), slicing takes the last element of the list by default. If you do not specify the first element ( e.g. [:7] ), the first element of the list [0] is taken by default.

Example

Example 1

Create a list with five elements.

namelist=['A','B','C','D','E']

Copy all the elements of the list into a new variable namelist2.

namelist2=namelist[:]

View the contents of the new variable.

>>> namelist2
['A', 'B', 'C', 'D', 'E']

The target variable is also a list and it contains all the elements of the variable source list.

Example 2

Create a list with five elements.

namelist=['A','B','C','D','E']

Copy only the second (B) and the third element (C) of the list.

namelist2=namelist[1:3]

The second element of the list has index [1] while the third [2].

The slicing selection range is [1,3].

  • 1 = the index of the first element to be copied
  • 3 = the index of the last element excluded from the selection

Print the contents of the new variable.

>>> namelist
['B', 'C']

In this case, Python only copied the elements in the range [1: 3] of slicing.

Note. The first element of a list always has an index [0]. The index [1] is associated with the second element of the list. The index [2] to the third, etc.
the reading of the list is sequential from index 0 to index n

https://how.okpedia.org/en/python/how-to-copy-a-list-in-python


Report an error or share a suggestion to enhance this page


Python List


FacebookTwitterLinkedinLinkedin