Slicing Sequences
Slicing is a powerful technique that allows you to extract specific portions of data from Python sequences such as lists, strings, and tuples. It provides you with the ability to finely control what data you need, whether it’s from the beginning, end, or anywhere in between. This slicing capability is governed by both positive and negative index systems, making it a versatile tool for data manipulation.
Slicing Index System
Consider the following index systems for a list:
Indexing Sequences | |
---|---|
Results in:
Easily access specific portions of a list using slicing. For example, to access the 2nd, 3rd, and 4th items of a list named days, you can use the following code:
Slicing Lists | |
---|---|
Would output:
Retrieve the first three items of a list by simply omitting the starting index:
Retrieving First 3 Items in a List | |
---|---|
Would result in:
To get the last three items, you can use negative indexing:
Negative Slicing of Lists | |
---|---|
Outputs:
For everything except the last item, exclude it by slicing until one element from the end:
Exclude the Last Item in a List | |
---|---|
Results in:
Similarly, you can exclude the last two items:
Exclude the Last 2 Items in a List | |
---|---|
Returns:
Slicing Strings and Tuples
Strings and tuples share the same slicing principles as lists. You can effortlessly extract portions of text from a string or elements from a tuple using slicing. For example, consider this example:
Would output: