Slicing in Python
Python Slicing Concepts
What is Slicing in Python?
Slicing in Python means extracting a portion (subset) of a sequence like a list, string, tuple, or NumPy array
using a range of indices.
Syntax:
sequence[start : stop : step]
- start: Index to start from (inclusive)
- stop: Index to stop at (exclusive)
- step: Interval between elements
Examples with a List:
numbers = [10, 20, 30, 40, 50, 60]
1. numbers[1:4] => [20, 30, 40]
2. numbers[:3] => [10, 20, 30]
3. numbers[3:] => [40, 50, 60]
4. numbers[::2] => [10, 30, 50]
5. numbers[::-1] => [60, 50, 40, 30, 20, 10] (Reverses list)
Slicing Strings:
text = "PYTHON"
1. text[1:4] => 'YTH'
2. text[::-1] => 'NOHTYP'
Slicing NumPy Arrays:
import numpy as np
Slicing in Python
a = np.array([[1, 2, 3],
[4, 5, 6]])
a[0, :] => [1 2 3] # First row
a[:, 1] => [2 5] # Second column
Slicing is a powerful feature in Python that helps access data quickly and efficiently without loops.