Understanding slicing in Python
- tinyytopic.com
- 0
- on Mar 23, 2023
Slicing in Python refers to the technique of selecting a range of elements from a sequence, such as a string, list, or tuple. Slicing is achieved by specifying a range of indices, separated by a colon, within square brackets following the sequence.
Here’s the syntax for slicing:
sequence[start:stop:step]
start
: The index where the slice starts (inclusive). Ifstart
is not specified, it defaults to 0.stop
: The index where the slice ends (exclusive). Ifstop
is not specified, it defaults to the end of the sequence.step
: The step size between elements in the slice. Ifstep
is not specified, it defaults to 1.
Let’s look at some examples:
>>> s = "hello world" >>> s[0:5] # select the first 5 characters 'hello' >>> s[6:] # select everything after the space 'world' >>> s[:5] # select everything up to the first space 'hello' >>> s[::2] # select every second character 'hlowrd' >>> s[::-1] # reverse the string 'dlrow olleh'
List of all possible Slice methods format:
- [start:end] – Returns the slice from ‘start’ index to ‘end-1’ index.
- [start:] – Returns the slice from ‘start’ index to the end of the sequence.
- [:end] – Returns the slice from the beginning of the sequence to ‘end-1’ index.
- [start:end:step] – Returns a slice from ‘start’ to ‘end-1’ index with ‘step’ intervals.
- [::-1] – Returns the reverse of the sequence.
- [:] – Returns a copy of the entire sequence.
- [::] – Returns a copy of the entire sequence.
- [start:end:step] – Returns a slice from ‘start’ to ‘end-1’ index with ‘step’ intervals.
- [-1] – Returns the last item of the sequence.
- [-n:] – Returns the last ‘n’ items of the sequence.
- [:-n] – Returns all the items of the sequence except the last ‘n’ items.
All possible sample code:
my_list = [1, 2, 3, 4, 5] # Get the first element print(my_list[0]) # Get the last element print(my_list[-1]) # Get the first three elements print(my_list[:3]) # Get the last two elements print(my_list[-2:]) # Get every other element starting from the second print(my_list[1::2]) # Reverse the list print(my_list[::-1]) # Get the second through fourth elements print(my_list[1:4]) # Get every other element starting from the first print(my_list[::2]) # Get every third element starting from the second to the second last element print(my_list[1:-1:3]) # Assign new values to elements using slice notation my_list[:3] = [0, 0, 0] print(my_list) # Delete elements using slice notation del my_list[-2:] print(my_list) # Copy the entire list using slice notation copy_list = my_list[:] print(copy_list)