Slicing list in Python
With the help of slicing, we can get the required elements from the list (sublist).
Slicing won't affect the original list. It will return the new list with the required elements.
starting index value will be included in the list and the ending index value will be excluded from the list.
numbers[0:3] will return the new sublist [10, 20, 30]. Index 3 i.e. value 40 will be excluded.
numbers[-4:-1] will return the new sublist [20, 30, 40]. Index -1 i.e value 50 will be excluded.
Slicing with default values
We can also use the default value in slicing by omitting either start index or end index.
The omitted first index will be set to 0.
The omitted end index will be set to length of the list (not end index of the list).
Copy of the List
We can get the copy of the whole list by using list[:].
This is very useful when we want to manipulate the list but don't want to change the actual contents of it.
Assignment to Slices
Assigning values to the sliced sublist.
Removing Elements from the List
We can remove any sublist from the list by replacing all the sublist elements with an empty list.
Clear the Whole List
We can also clear the whole list by replacing all the elements with an empty list.