2.3.1. Good Practices

2.3.1.1. Stop using = operator to create a copy of a Python list. Use copy method instead

When you create a copy of a Python list using the = operator, a change in the new list will lead to the change in the old list. It is because both lists point to the same object.

l1 = [1, 2, 3]
l2 = l1 
l2.append(4)
l2 
[1, 2, 3, 4]
l1 
[1, 2, 3, 4]

Instead of using = operator, use copy() method. Now your old list will not change when you change your new list.

l1 = [1, 2, 3]
l2 = l1.copy()
l2.append(4)
l2 
[1, 2, 3, 4]
l1
[1, 2, 3]

2.3.1.2. deepcopy: Copy a Nested Object

If you want to create a copy of a nested object, use deepcopy. While copy creates a shallow copy of the original object, deepcopy creates a deep copy of the original object. This means that if you change the nested children of a shallow copy, the original object will also change. However, if you change the nested children of a deep copy, the original object will not change.

from copy import deepcopy

l1 = [1, 2, [3, 4]]
l2 = l1.copy() # Create a shallow copy
l2[0] = 6
l2[2].append(5)
l2 
[6, 2, [3, 4, 5]]
# [3, 4] becomes [3, 4, 5]
l1 
[1, 2, [3, 4, 5]]
l1 = [1, 2, [3, 4]]
l3 = deepcopy(l1) # Create a deep copy
l3[2].append(5)
l3  
[1, 2, [3, 4, 5]]
# l1 stays the same
l1 
[1, 2, [3, 4]]

2.3.1.3. Enumerate: Get Counter and Value While Looping

Are you using for i in range(len(array)) to access both the index and the value of the array? If so, use enumerate instead. It produces the same result but it is much cleaner.

arr = ['a', 'b', 'c', 'd', 'e']

# Instead of this
for i in range(len(arr)):
    print(i, arr[i])
0 a
1 b
2 c
3 d
4 e
# Use this
for i, val in enumerate(arr):
    print(i, val)
0 a
1 b
2 c
3 d
4 e

2.3.1.4. Difference between list append and list extend

If you want to add a list to another list, use the append method. To add elements of a list to another list, use the extend method.

# Add a list to a list
a = [1, 2, 3, 4]
a.append([5, 6])
a
[1, 2, 3, 4, [5, 6]]
a = [1, 2, 3, 4]
a.extend([5, 6])

a
[1, 2, 3, 4, 5, 6]