Most methods that result in a list are in-place operations. These are operations that change a Python object directly without creating a new object of the same type. They can be best explained by looking at the following example, reverse:
L = [1, 2, 3] L.reverse() # the list L is now reversed L # [3, 2, 1]
Be aware of in-place operations. You might be tempted to write:
L=[3, 4, 4, 5] newL = L.sort()
This is correct Python. But in-place operations return the value None and alter the list. Therefore, using the variable newL as if it was a (sorted) list, for example, as
print(newL[0])
causes an error:
TypeError: 'NoneType' object is not subscriptable
Here, we demonstrate in-place list operations:
L = [0, 1, 2, 3, 4] L.append(5) # [0, 1, 2, 3, 4, 5] L.reverse() # [5, 4, 3, 2, 1, 0] L.sort() # [0, 1, 2, 3, 4, 5] L.remove(0) # [1, 2, 3, 4, 5] L.pop() # [1, 2, 3, 4] L.pop() # [1, 2, 3] L.extend(['a','b','c&apos...