Arrays · 8 / 23 Theory

Advanced slicing and sorting

Slices list[start:stop:step] can be used with negative indexes, steps and omitted limits, both to read and to assign or delete parts.

Slicing with steps and negative indexes

n = [10, 20, 30, 40, 50, 60]

print(n[1:4])      # [20, 30, 40]
print(n[::2])      # [10, 30, 50]   every 2nd
print(n[::-1])     # [60, 50, 40, 30, 20, 10]   reversed
print(n[-2:])      # [50, 60]       the last two
print(n[:-1])      # [10, 20, 30, 40, 50]   all but the last

n[1:3] = [0, 0, 0]       # assigning to a slice can change the length
print(n)           # [10, 0, 0, 0, 40, 50, 60]
del n[::2]               # delete with a step
print(n)           # [0, 0, 50]

A slice always returns a new list and never fails for going out of range: n[2:100] simply goes up to the end.

sorted versus sort

There are two ways to sort. sorted(iterable) returns a new list and leaves the original untouched; list.sort() sorts the list itself and returns None. A very common mistake is writing x = x.sort(), which leaves x as None.

marks = [7, 3, 9, 5]

sorted_list = sorted(marks)        # returns a NEW list
print(sorted_list, marks)          # [3, 5, 7, 9] [7, 3, 9, 5]

r = marks.sort()                # sorts the ORIGINAL list and returns None
print(r, marks)                 # None [3, 5, 7, 9]

words = ["pear", "fig", "banana", "kiwi"]
print(sorted(words, key=len))                  # ['fig', 'pear', 'kiwi', 'banana']
print(sorted(words, key=len, reverse=True))    # ['banana', 'pear', 'kiwi', 'fig']
print(sorted("python"))                           # ['h', 'n', 'o', 'p', 't', 'y']  (accepts any iterable)
  • Both accept key= (a function that gives the sort key) and reverse=True.
  • Sorting is stable: elements with the same key keep their relative order. That is why you can sort in two passes, first by the secondary criterion and then by the main one.
  • If the key is a tuple, it sorts by the first element and, on a tie, by the next one.

You practice it in Rotate a list, Merge two sorted lists and Sort by several criteria.