5 March 2021

Open Lab

Questions can be posted here for the benefit of both classes

This sorts the list in-place. Use it if you don't care about keeping its order. Danger: if you pass a list to a function and use it to sort that list, the list will be sorted in the caller, too.


>>> x = [4,2,9,7,5]
>>> x
[4, 2, 9, 7, 5]
>>> x.sort()
>>> x
[2, 4, 5, 7, 9]

This returns a sorted copy of the list and does not change the original.


>>> x = [4,2,9,7,5]
>>> y = sorted(x)
>>> x
[4, 2, 9, 7, 5]
>>> y
[2, 4, 5, 7, 9]

Sorting works only for homogeneous lists.


>>> x = ["cows", 42, True, [1,2,3]]
>>> x.sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  TypeError: '<' not supported between instances of 'int' and 'str'
  >>>