array slicing का simply मतलब किसी array में से need के according particular elements select करना। पिछले topic में आपने पढ़ा कि , array से simply index pass करके values निकालते थे , लेकिन इस topic में आप array slicing के बारे में पढ़ेंगे।

Array Slicing Syntax

arr_var[start:end:step]

  1. start : यह start index होती है जहाँ से elements select करने हैं, by default 0 होती है।

  2. end : यह end index है जहाँ तक elements select करने हैं , by default इसकी value Current array length के बराबर होती है।

  3. step : step means कितने elements को छोड़कर elements select करने हैं , by default इसकी value 1 होती है।

Array Slicing Example

Copy Fullscreen Close Fullscreen Run
#import numpy module.
import numpy as np
arr = np.array([12,23,12,6,77,878,78,785,6,45,34,45])
#selecting all elements from the index 2.
print(arr[2:])
#selecting all elements from the index 2 to 5.
print(arr[2:5])
#selecting all elements from the index 0 to 5.
print(arr[:5])
Output
C:\Users\Rahulkumar\Desktop\python>python module_numpy.py
[ 12   6  77 878  78 785   6  45  34  45]
[12  6 77]
[12 23 12  6 77]

Negative Array Slicing

ठीक इसी तरह से , negative slicing भी कर सकते हैं।

Copy Fullscreen Close Fullscreen Run
import numpy as np
arr = np.array([12,23,12,6,77,878,78,785,6,100,34,45])
#selecting all elements from start to second last.
print(arr[:-2])
#selecting all elements from the index 5 start to 3rd last.
print(arr[5:-3])
print(arr[-5:-2])
Output
C:\Users\Rahulkumar\Desktop\python>python module_numpy.py
[ 12  23  12   6  77 878  78 785   6 100]
[878  78 785   6]
[785   6 100]
Multi dimensional Array Slicing

जिस तरह से पिछले topic में आपने पढ़ा कि , कैसे multi dimensional array elements को कैसे access करते हैं , ठीक उसी तरह से slicing भी करते हैं।

Copy Fullscreen Close Fullscreen Run
import numpy as np
arr = np.array([ [45,3,4,56] , [23,45,56,34], [78,89,6,7] ])
#selecting 1st element's all elements from the index 2.
print(arr[0, 2:])
#it is same as : .
print(arr[0][2:])

#selecting 2nd element's all elements from the index 1 to 3.
print(arr[1, 1:3])
#it is same as : .
print(arr[1][1:3])
Output
C:\Users\Rahulkumar\Desktop\python>python module_numpy.py
[ 4 56]
[ 4 56]
[45 56]
[45 56]

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! My name is Rahul Kumar Rajput. I'm a back end web developer and founder of learnhindituts.com. I live in Uttar Pradesh (UP), India and I love to talk about programming as well as writing technical tutorials and tips that can help to others.

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers