Informatics Practices · Ch 4 — Working with Lists and Dictionaries
Slicing
Slicing
Indexing pulls out one element; slicing pulls out a whole run of them. A slicing operation creates a new list by taking out elements from an existing list — you name the range of indexes you want, and Python hands back those elements as a fresh list, leaving the original untouched.
All the examples below work on one list:
>>> list1 = ['Red','Green','Blue','Cyan','Magenta','Yellow','Black']
The basic form: list1[start:stop]
The slice list1[start:stop] takes the elements from index start up to but not including index stop:
>>> list1[2:6] # elements at indexes 2 to 5
['Blue', 'Cyan', 'Magenta', 'Yellow']
The element at index 6 ('Black') is not included — the second index marks where the slice stops, not the last element taken. This half-open behaviour is the heart of every slicing rule that follows.
When the indexes are unusual
Slicing is forgiving where plain indexing is strict:
>>> list1[2:20] # second index out of range
['Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']
>>> list1[7:2] # first index greater than second
[]
- If the second index runs beyond the end of the list, there is no
IndexError— the slice is simply truncated at the end of the list. - If the first index is greater than the second, the range is empty, and the result is an empty list
[].
Leaving an index out
Either boundary may be omitted, and Python fills in the obvious default:
>>> list1[:5] # first index missing: start from index 0
['Red', 'Green', 'Blue', 'Cyan', 'Magenta']
A missing first index means "from the beginning"; the slice above returns the sublist from index 0 to 4.
Slicing with a step size
A third value inside the brackets sets a step size — how far to jump between the elements taken:
>>> list1[0:6:2] # every second element from index 0 to 5
['Red', 'Blue', 'Magenta']
With step 2, the slice picks the elements at indexes 0, 2 and 4 within the given range.
Negative indexes in slices
Negative index values work in slices just as in indexing, counting from the right:
>>> list1[-6:-2] # elements at indexes -6, -5, -4, -3
['Green', 'Blue', 'Cyan', 'Magenta']
The stop position -2 is again excluded — only the elements at -6, -5, -4 and -3 are sliced out.
Omitting both boundaries
With both the first and the last index missing, the slice covers the entire list, and the step still applies:
>>> list1[::2] # step size 2 over the whole list
['Red', 'Blue', 'Magenta', 'Black']
Reversing a list with a negative step
A negative step size walks the list backwards, so the whole list in reverse order is one slice away:
>>> list1[::-1]
['Black', 'Yellow', 'Magenta', 'Cyan', 'Blue', 'Green', 'Red']
list1[::-1] is the standard idiom for accessing a list in reverse order — no loop needed. …