Slicing lists

Slicing is a form of extended indexing which allows us to refer to portions of a list. To use it we pass the start and stop indices of a half-open range, separated by a colon, as the square-brackets index argument. Here's how:

>>> s = [3, 186, 4431, 74400, 1048443]
>>> s[1:3]
[186, 4431]

See how the second index is one beyond the end of the returned range. The slice [1:4] . Slicing extracts part of a list. The slice range is half-open, so the value at the stop index is not included:

Figure 5.7: The half-open slice range

This facility can be combined with negative indices. For example, to take all elements except the first and last:

>>> s[1:-1]
[186, 4431, 74400]

The slice s[1:-1] is useful for excluding the first and last elements of a list as shown in the following image:

Figure 5.8:  Excluding  elements

Both the start and stop indices are optional. To slice all elements from the third to the end of the list:

>>> s[3:]
[74400, 1048443]

The slice s[3:] retains all the elements from the fourth, up to and including the last element, as shown in the following diagram 

Figure 5.9: Slice-to-end

To slice all elements from the beginning up to, but not including, the third:

>>> s[:3]
[3, 186, 4431]

The slice s[:3] retains all elements from the beginning of the list up to, but not including, the fourth element as shown in the following diagram:

Figure 5.10: Silce from the beginning

Notice that these two lists are complementary, and together form the whole list, demonstrating the convenience of the half-open range convention.

Figure 5.11: Complementary slices

Since both start and stop slice indices are optional, it's entirely possible to omit both and retrieve all of the elements:

>>> s[:]
[3, 186, 4431, 74400, 1048443]

This is a called a full slice, and it's an important technique in Python.

The slice s[:] is the full-slice and contains all of the elements from the list. It's an important idiom for copying lists:

Figure 5.12: The full-slice
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset