python cut array code example
Example 1: python how to slice lists
# Basic syntax:
your_list[start:stop:step]
# Note, Python is 0-indexed
# Note, start is inclusive but stop is exclusive
# Note, if you leave start blank, it defaults to 0. If you leave stop
# blank, it defaults to the length of the list. If you leave step
# blank, it defaults to 1.
# Note, a negative start/stop refers to the index starting from the end
# of the list. Negative step returns list elements from right to left
# Example usage:
your_list = [0, 1, 2, 3, 4, 5]
your_list[0:5:1]
--> [0, 1, 2, 3, 4] # This illustrates how stop is not inclusive
# Example usage 2:
your_list = [0, 1, 2, 3, 4, 5]
your_list[::2] # Return list items for even indices
--> [0, 2, 4]
# Example usage 3:
your_list = [0, 1, 2, 3, 4, 5]
your_list[1::2] # Return list items for odd indices
--> [1, 3, 5]
# Example usage 4:
your_list = [0, 1, 2, 3, 4, 5]
your_list[4:-6:-1] # Return list items from 4th element from the left to
# the 6th element from the right going from right to left
--> [4, 3, 2, 1]
# Note, from the right, lists are 1-indexed, not 0-indexed
Example 2: array slicing python
#slicing arrays:
#generic sampling is done by
#arr[start:end] -> where start is the starting index and end is ending idx
>>> import numpy as np
>>> arr = np.array([1,2,3,4,5])
>>> print(arr[1:5]) #starting idx 1 to ending index 4
[2 3 4 5]#it will print from starting idx to ending idx-1
#if you leave the ending index blank it will print all
#from the starting index till end
>>> arr = np.array([2,6,1,7,5])
>>> print(arr[3:])
[7 5]
>>> print(arr[:3]) #if you leave the starting index blank it will print from 0 index to the ending idx-1\
[2 6 1]
>>> print(arr[:])
[2 6 1 7 5]
#leaving both the index open will print the entire array.
##########STEP slicing########
#if you want to traverse by taking steps more than 1
#we use step slicing in that case
#syntax for step slicing is : arr[start:end:step]
>>> arr = np.array([2,6,1,7,5,10,43,21,100,29])
>>> print(arr[1:8:2])#we have taken steps of two
[ 6 7 10 21]