Alex P
0
Q:

slicing in python

word = "Example"

# Obtain the first 3 characters of "Example"
# E x a m p l e
# 0 1 2 3 4 5 6
# First 3 characters = "Exa"
sliced_word = word[:3] # Gives you "Exa"

# Everything after character #3 = "mple"
second_sliced_word = word[3:] # Gives you "mple"
4
a = [1,2,3,4,5]
a[m:n] # elements grrater than equal to m and less than n
a[1:3] = [2,3]
3
# array[start:stop:step]

# start = include everything STARTING AT this idx (inclusive)
# stop = include everything BEFORE this idx (exclusive)
# step = (can be ommitted) difference between each idx in the sequence

arr = ['a', 'b', 'c', 'd', 'e']

arr[2:] => ['c', 'd', 'e']

arr[:4] => ['a', 'b', 'c', 'd']

arr[2:4] => ['c', 'd']

arr[0:5:2] => ['a', 'c', 'e']

arr[:] => makes copy of arr
3
#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]


 
  
 
1

New to Communities?

Join the community