Slicing

As with strings, in order to get a single value from the list, you need to use its index in the square brackets after the value, as shown in the following code snippet:

>>> fruits[0]
'banana'

You can also obtain a subset of list values by using slices: intervals of indexes that are defined by two numbers and separated by a colon. The numbers represent start and end indices; the former number is inclusive, but the latter number is not. If one or both numbers are missing, then Python assumes those to be the ends of the list. Here is an example:

>>> fruits[0:2]
['banana', 'apple']

>>> fruits[:2]
['banana', 'apple']

In both cases, we're pulling the first two elements. In this case, it doesn't matter whether we include 0 or not.

This is exactly the same interface we used with strings. As with strings, we can use negative indices. For example, -1 will represent the last element in the list, no matter what is the actual index of the value. One more feature of slicing is its ability to define the step of the increase. By default, the step is equal to 1. However, if you state it as 2, only even elements will be retrieved:

>>> fruits[::2]
['banana', 'orange', 'pineapple']

 Similarly, -1 will retrieve all elements, but in the reverse order:

>>> fruits[:2:-1]
['melon', 'pineapple', 'plum']

Slicing is widespread across data structures. Apart from lists and strings, it can be used with tuples (see the next section) and a few other types, so it is a good idea to master the skill of slicing.