Indexing and Slicing Concept#10203
Indexing and slicing are operations used to access elements of a collection.
- Indexing means accessing a single element using its position. In Python, indexing generally starts from
0, and negative indices can be used to access elements from the end.
- Slicing means extracting a portion of a collection by specifying a range of positions. The start position is included, but the stop position is excluded.
These operations are commonly associated with sequence types, such as strings, lists, and tuples.
For example:
numbers = [10, 20, 30, 40, 50]
print(numbers[2]) # 30 — Indexing
print(numbers[1:4]) # [20, 30, 40] — Slicing
Important: Not every collection supports indexing and slicing. Dictionaries provide access through keys, while sets do not support either operation. The operations supported by a collection depend on its type.