My Coding > Programming language > Python > Python LIST HowTo

Python LIST HowTo (Page: 3)

Go to Page:

  1. List in Python;
  2. Python List Cheat Sheet;
  3. How To copy List in Python;

Shallow copying lists in Python

Shallow list copying in Python can only be used when it is known, that the list has only one layer of stored data.

Use method .copy()


L1 = [1, 2, 3]
L2 = L1.copy()
L2[0] = 'ONE'
print(L1) # [1, 2, 3]
print(L2) # ['ONE', 2, 3]

Use full slice [:]


L1 = [1, 2, 3]
L2 = L1[:]
L2[0] = 'ONE'
print(L1) # [1, 2, 3]
print(L2) # ['ONE', 2, 3]

Use constructor list()


L1 = [1, 2, 3]
L2 = list(L1)
L2[0] = 'ONE'
print(L1) # [1, 2, 3]
print(L2) # ['ONE', 2, 3]

Use interpolation [*list]


L1 = [1, 2, 3]
L2 = [*L1]
L2[0] = 'ONE'
print(L1) # [1, 2, 3]
print(L2) # ['ONE', 2, 3]

Use function copy() from module copy


from copy import copy
L1 = [1, 2, 3]
L2 = copy(L1)
L2[0] = 'ONE'
print(L1) # [1, 2, 3]
print(L2) # ['ONE', 2, 3]

Multiplication by number list * 1

This can make one copy of the list of with using other numbers, you can make repetition of lists


L1 = [1, 2, 3]
L2 = L1 * 1
L3 = L1 * 2
L2[0] = 'ONE'
print(L1) # [1, 2, 3]
print(L2) # ['ONE', 2, 3]
print(L3) # [1, 2, 3, 1, 2, 3]

Fastes way of shallow copying

The difference in copying performance can only be observed from small (len()<1000) elements. For bigger lists, shallow copies are approximately similar in their performance. Almost 10 times difference for very small lists (len()<10) and about 5 times difference for lists of medium size (len()<100) can actually be ignored in most of the cases. The final performance will be distributed like that, from fastest to slowest:

  • fastest - L1 * 1, [*L1]
  • L1.copy(), L1[:]
  • list(L1)
  • slowest - copy(L1)
    • Deep copying lists in Python

      To make a full copy of the list content in Python, it is necessary to use deepcopy() function from module copy. Only this way can guarantee creating of the full independent copy of your lists. Usually, in the program, if you are not sure of the lists content, it is better to use deepcopy rather than shallow copy

      
      from copy import deepcopy
      
      L1 = [[1, 2],[3, 4],[5, 6]]
      L2 = deepcopy(L1)  
      L2[0][0] = 'ONE'
      print(L1) # [['1', 2], [3, 4], [5, 6]]
      print(L2) # [['ONE', 2], [3, 4], [5, 6]]

      Wrong copying lists in Python

      
      L1 = [1, 2, 3]
      L2 = L1       # This is only copying reference to list!!!!
      print(id(L1)) # 139890576959176
      print(id(L2)) # 139890576959176
      L2[1] = 'TWO'
      print( L1 )   # [1, 'TWO', 3]

      Go to Page: 1; 2; 3;


      Published: 2021-09-13 08:23:41
      Updated: 2021-10-24 11:58:41

Last 10 artitles


9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.