Important Notice:

Slicing in List

Slicing in List

8 views 2 min read
Slicing in List :-

 

Python में Slicing in List का अर्थ है List में से एक से अधिक elements के किसी particular part (भाग) को प्राप्त करना। Slicing की सहायता से हम List के elements की एक range को आसानी से access कर सकते हैं।

Slicing में start index शामिल होता है, लेकिन stop index शामिल नहीं होता।

English

Slicing in List means extracting a particular portion or range of elements from a list. Slicing allows us to access multiple elements of a list at once.

The start index is included, but the stop index is excluded.

Syntax:-

list[start:stop]

Example:-

numbers = [10, 20, 30, 40, 50]

print(numbers[1:4])

Output:-

[20, 30, 40]

Because:-

यहाँ:

Element :  10   20   30   40   50
Index   :      0    1      2    3     4

numbers[1:4] में:

Index 1 → 20 शामिल होगा।
Index 2 → 30 शामिल होगा।
Index 3 → 40 शामिल होगा।
Index 4 → include नहीं होगा।

इसलिए output:

[20, 30, 40]
 
Slicing with Start Index :-

यदि केवल start index दिया जाए, तो List start index से end तक के elements return करती है।

numbers = [10, 20, 30, 40, 50]

print(numbers[2:])

Output:-

[30, 40, 50]

यहाँ index 2 से लेकर last element तक के elements प्राप्त होते हैं।
 

Slicing with Stop Index :-

यदि start index नहीं दिया जाए, तो slicing beginning से दिए गए stop index तक होती है।

numbers = [10, 20, 30, 40, 50]

print(numbers[:3])

Output:-

[10, 20, 30]

यहाँ index 3 include नहीं होता।

Slicing with Step :-

Slicing में step का उपयोग elements के बीच का gap निर्धारित करने के लिए किया जाता है।

Syntax:-

list[start:stop:step]

Example:-

numbers = [10, 20, 30, 40, 50, 60]

print(numbers[0:6:2])

Output:-

[10, 30, 50]

Because:-

यहाँ step = 2 है, इसलिए हर दूसरा element लिया गया।

Negative Indexing with Slicing :-

Slicing में negative indexes का भी उपयोग किया जा सकता है।

numbers = [10, 20, 30, 40, 50]

print(numbers[-4:-1])

Output:-

[20, 30, 40]

Important Point :-

Slicing में stop index हमेशा excluded होता है।

Common Examples:-
numbers = [10, 20, 30, 40, 50]

print(numbers[:3])     # [10, 20, 30]
print(numbers[2:])     # [30, 40, 50]
print(numbers[1:4])    # [20, 30, 40]
print(numbers[::2])    # [10, 30, 50]

Related Notes