Python List Slicing
To access a range of items in a list, you need to slice a list. One way to do this is to use the simple slicing operator :
With this operator you can specify where to start the slicing, where to end and specify the step.
Slicing a List
If L is a list, the expression L [ start : stop : step ] returns the portion of the list from index start to index stop, at a step size step.
Syntax
Basic Example
Here is a basic example of list slicing.
Note that the item at index 7 'h'
is not included.
Slice with Negative Indices
You can also specify negative indices while slicing a list.
Slice with Positive & Negative Indices
You can specify both positive and negative indices at the same time.
Specify Step of the Slicing
You can specify the step of the slicing using step parameter. The step parameter is optional and by default 1.
Negative Step Size
You can even specify a negative step size.
Slice at Beginning & End
Omitting the start index starts the slice from the index 0. Meaning, L[:stop]
is equivalent to L[0:stop]
Whereas, omitting the stop index extends the slice to the end of the list. Meaning, L[start:]
is equivalent to L[start:len(L)]
Reverse a List
You can reverse a list by omitting both start and stop indices and specifying a step as -1.
Modify Multiple List Values
You can modify multiple list items at once with slice assignment. This assignment replaces the specified slice of a list with the items of assigned iterable.
Insert Multiple List Items
You can insert items into a list without replacing anything. Simply specify a zero-length slice.
You can insert items into the middle of list by keeping both the start and stop indices of the slice same.
Delete Multiple List Items
You can delete multiple items out of the middle of a list by assigning the appropriate slice to an empty list.
You can also use the del statement with the same slice.
Clone or Copy a List
When you execute new_List = old_List
, you don’t actually have two lists. The assignment just copies the reference to the list, not the actual list. So, both new_List
and old_List
refer to the same list after the assignment.
You can use slicing operator to actually copy the list (also known as a shallow copy).
No hay comentarios:
Publicar un comentario