|k8hThTh`hTh`hyk8jyh[hyjyh[hyjyh[jyh[yk/y[hy`Vyh[hyyh[hyyh[pyhzg_Fy[FFFiBbAAEeBBfeX-|F55555WC 865VBW 865VC 86565VB 56VBW A65VC 6Z 6}5ZW 9V-
Slice.` A snake appears near your foot. It moves from the invisible to the visible. Our vision reveals (like a slice) only a part of the world.`A Python slice` extracts elements, based on a start and stop. We take slices on many types in Python. We specify an optional first index, an optional last index, and an optional step.`Syntax notes.` The special syntax for this operation is at first confusing. But with practice, slicing becomes easy. When we omit a value, a default is used. `List.` This program takes a slice of a list. We first create a list with five numeric elements. We specify in the slice two values: 1 and 3. At index 1, we have the value 200. `Python elements begin at index 0. So the first index (for slices or indexes) is zero.`We continue up to (but not including) index 3, which is the value 400. So our result list has 200 and 300 in it.`Resize list.` A slice can be used to resize a list. We can remove elements past a certain length. This makes the list smaller (reduces its size). We can also pad a list with new elements. `Resize List `resize-list-python`Negative.` The second index in slice notation may be negative. This means counting begins from the last index. So a negative one means the same as "length minus one." `So: `You can reduce an array length by one by using a second index of negative one. Leave the first index undefined.`Start, end.` In slicing, if you omit the first or second index, it means "start" or "end." This is clearer than specifying 0 or the length. `Programs with less confusing syntax tend to develop fewer bugs over time. So lazy programmers are sometimes the best ones.`Strings.` We use the slice notation on strings. In this example, we omit the first index to start at the beginning, and then consume four characters total. We extract the first four letters. `Substring `substring-python`Copy.` With slicing, we can copy sequences like lists. We assign a new list variable to a slice with no specified start or stop values. So the slice copies the entire list and returns it. `Copy List `copy-list-python`Step.` There is a third, optional index used in slicing: the step. If the step is two, we advance two places after an element is copied. So we can skip over elements. `This allows us to quickly access all odd or even elements in an array. No complicated loops are required.`Invalid.` Slicing is safe. It will cause no errors assuming you use integers as arguments. Often when programming, a tiny error will cause an extreme disaster and the program will implode. `However: `Slicing alleviates some of these hassles. But this too can be a problem. Our program might silently fail, causing confusion later.`TypeError.` Arguments to slice must be of a valid type. They cannot be strings or collections. If an object has an __index__ method, it can be used in place of an integer as a slice index. `Exceptions `error-python`Tuple.` Tuples too may be sliced. Slicing notation is standardized throughout Python 3 objects. So once you learn it on lists or strings, you can slice tuples without much trouble. `Tuple `tuple-python`Object.` There is a slice built-in method. It returns a slice object. As the documentation states, slice objects are not used in core types, but are sometimes needed in numerical libraries. `So: `If you are trying to slice a string, list or other built-in type, pay no attention to the slice method. It won't help you.`A syntax form.` Slicing is convenient. Built into the Python language, it is often unavailable in other languages, making copies and extractions hard. We take substrings with slice notation.`Other operations.` With slices, we copy lists and resize lists. This syntax is versatile and expressive. It is compact and provides useful defaults when values are omitted.
UVWSlice syntax Vms:W UUU VVs from... WVs[1:3] W V 1 through index 3. WVs[2:-1]W V 2 through index one from last. WVs[:2] W V through index 2. WVs[2:] W V 2 through end. WVs[::2] W V through end, skipping ahead 2 places each time.W VsV[100, W200W, W300W, 400, 500]W # VVs from second indexVthird index. WsliceVWVs[1:3]W V(slice) W [200, 300]W VsV[100, 200, W300W, W400W, 500]W # Slice from third indexVindex one from last. WsliceVVs[W2:-1W] V(slice) W [300, 400]W VsV[W100W, W200W, 300, 400, 500]W # Slice from startVsecond index. WsliceVVs[W:2W] V(slice)W # Slice from second indexVend. WsliceVVs[W2:W] V(slice) W [100, 200] [300, 400, 500]W wordV"WsomeWthing"W # Vfirst four cVs. WpartVword[:4] V(part) W someW VsVW"AaBbCcDdEe"W # Ving at 0Vcontinuing until end, take every other char. WevensVVs[W::2W] V(evens) W ABCDEW VsV[9, 8, 7, 6]W # This causes no error. WtestVVs[555:555:5555] V(test)W VsV["carrot", "rat"]W # Must use indexes or None. WtestVVs["friend":"dog"] V(test) W Traceback (most recent call last): File "...", line 7,V<module> UtestVVs["friend":"dog"] WTypeErrorW: slice indices must be Vegers or None Uor have an __index__ mVW W# CV a slice object. WeVVWsliceW(1, 10, 0) V(eV.start, eV.stop, eV.step) W 1 10 0W
(+=7-\_04slices listslices, negative second indexslices, starts and endsslices stringstep, slicesinvalid indexescauses TypeErrorcreates slice object