L

Slice Values

Slicing details were also described in Section 11.1.1.

Python is a zero-indexed language (things start counting from zero), and is also left inclusive, right exclusive you are when specifying a range of values. This applies to objects like lists and Series, where the first element has a position (index) of 0. When creating ranges or slicing a range of values from a list-like object, we need to specify both the beginning index and the ending index. This is where the left inclusive, right exclusive terminology comes into play. The left index will be included in the returned range or slice, but the right index will not.

Think of items in a list-like object as being fenced in. The index represents the fence post. When we specify a range or a slice, we are actually referring to the fence posts, so that everything between the posts is returned.

Figure L.1 illustrates why this may be the case. When we slice from 0 to 1, we get only one value back; when we slice from 1 to 3, we get two values back.

l = ['one', 'two', 'three']

print(l[0:1])
['one']
print(l[1:3])
['two', 'three']
Images

Figure L.1 Think of Slicing Values as Referring to the Fence Posts

The slicing notation used, :, comes in two parts. The value on the left denotes the starting value (left inclusive), and the value on the right denotes the ending value (right exclusive). We can leave one of these values blank, and the slicing will start from the beginning (if we leave the left value blank) or go to the end (if we leave the right value blank).

print(l[1:])
['two', 'three']
print(l[:3])
['one', 'two', 'three']

We can add a second colon, which refers to the “step”. For example, if we have a step value of 2, then for whatever range we specified using the first colon, the returned value will be every other value from the range.

# get every other value starting from the first value
print(l[::2])
['one', 'three']
..................Content has been hidden....................

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