Basic Slicing Syntax
The general syntax for slicing a list is:- The element at the “start” index is included.
- The element at the “end” index is excluded; slicing stops just before it.
Slicing with Single Indices
If you provide only one index, Python interprets it differently based on its position in the slicing expression:-
Only a Starting Index:
The slice will include elements from the given start index to the end of the list. -
Only an Ending Index:
The slice will include elements from the beginning of the list up to, but not including, the specified end index.
Using Negative Indices
Negative indices are particularly useful when you don’t want to calculate the exact length of a list. They allow you to start counting from the end of the list. For example, to create a new list that excludes the first and last elements:Copying the Entire List
If no indices are provided, slicing makes a complete copy of the list:Creating a copy using slicing produces a new list in memory. Therefore, modifying the new list will not affect the original list.
Slicing vs. Assignment
When you assign one list to another, both variables point to the same list in memory. Any changes made to the list using one variable will be reflected through the other:Using the del Keyword with Slicing
Thedel keyword can be used alongside slicing to remove multiple elements from the original list. For example, to delete a slice from a list:
del without any indices, it will remove all elements, resulting in an empty list.
Be careful when using the
del keyword, as it modifies the original list permanently.Summary
Slicing is a powerful feature in Python that allows you to work with subsets of lists efficiently. Here’s what you learned:- Use
list[start:end]to extract a portion of a list. - Omitting the start or end index enables flexible slicing.
- Negative indices help target elements based on their position from the end.
- A slice without indices creates a copy of the list.
- Using
delwith slicing modifies the original list.