Cutting Up a List
You need to make a sublist of a list using a range of the original list’s elements.
Use the [:] Python language construction. The following example returns a list containing the elements of the original list from index position 1 to index position 2 (the number after the : is exclusive):
>>> l = [“a”, “b”, “c”, “d”] >>> l[1:3] [‘b’, ‘c’] |
Note that the character positions start at 0, so a position of 1 means the second character in the string and 5 means the sixth, but the character range is exclusive at the high end, so the letter d is not included in this example.
Discussion
The [:] notation is actually quite powerful. You can omit either argument, in which case the start or end of the list is assumed as appropriate. For example:
>>> l = [“a”, “b”, “c”, “d”] >>> l[:3] [‘a’, ‘b’, ‘c’] >>> l[3:] [‘d’] >>> |
You can also use negative indices to count back from the end of the list. The following example returns the last two elements in the list:
>>> l[-2:] [‘c’, ‘d’] |
Incidentally, l[:-2] returns [‘a’, ‘b’] in the preceding example.
See Also
All the recipes between Recipes 6.1 and 6.11 involve the use of lists.
See Recipe 5.15 where the same syntax is used for strings.