Array Slicing in Python

array1 = [‘a’, ‘b’, ‘c’,’d’,’e’,’f’]
array1[1:4] 
Output: ['b', 'c', 'd']
array1[1:4:2]
Output: ['b', 'd']
array1[1:]
Output: ['b', 'c', 'd', 'e', 'f']
array1[:4]
Output: ['a', 'b', 'c', 'd']
array1[:]
Output: ['a', 'b', 'c', 'd', 'e', 'f']
arrayname[start:end:step, start:end:step]
# importing numpy package for creating 2D Array
import numpy as np
#Creating 2D Array
array2 = np.array([[1,2,3,4],
[2,3,4,5],
[3,4,5,6],
[4,5,6,7]
])
#Slicing Operation on 2D Array
# to return all rows and only first two columns from the array defined.
array2[:,:2]
Output: array([[1, 2],
[2, 3],
[3, 4],
[4, 5]])
# to return from second row and first two columns
array2[1:,:2]
Output: array([[2, 3],
[3, 4],
[4, 5]])

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Greeshma Lakshmi

Greeshma Lakshmi

An enthusiast in the field of Data Science and Technology