Indexing & Slicing in List
1. Indexing in Lists
Indexing means accessing individual items in a list using their position (index).
Index always starts from 0 in Python.
Python also allows negative indexing. Here, -1 refers to the last
element, -2 to the second last, and so on.
So, indexing goes left to right with 0, 1, 2... and
right to left with -1, -2, -3....
This makes it easy to access elements from both ends of the list.
Index positions in a List
Below shows how positive and negative indexes work on a list:
# Positive index: 0 1 2 3
# -----------------------------
# List items: ["apple", "banana", "cherry", "mango"]
# Negative index: -4 -3 -2 -1
Example:
fruits = ["apple", "banana", "cherry", "mango"]
print(fruits[1]) # positive index
print(fruits[-1]) # negative index
Output:
banana
mango
Explanation:
fruits[1]gives the item at index 1, i.e.,banana.fruits[-1]gives the last item, i.e.,mango.
Summary of indexing:
- Indexing helps to get a single item using its position.
- Negative indexing starts from end, with
-1as last item.
2. Slicing in Lists
Slicing means getting a part (sub-list) from the original list.
It uses start:stop:step inside square brackets. It does not change the original list.
Note: Slicing does not include the element at stop
index.
For example, if stop = 4, it takes elements up to index 3.
Syntax:
list_name[start : stop : step]
Examples:
numbers = [10, 20, 30, 40, 50, 60]
1. Slicing with start and stop:
print(numbers[1:4])
Output:
[20, 30, 40]
Explanation:
start = 1, so it starts from index 1 (20).stop = 4, so it goes up to index 3 (40).- It does not include index
4(50). That’s why we say it stops at(stop - 1).
2. Omitting start (defaults to 0):
print(numbers[:3])
Output:
[10, 20, 30]
Explanation:
- Starts from beginning (index
0). - Goes up to
(stop-1 = 2).
3. Omitting stop (defaults to end):
print(numbers[3:])
Output:
[40, 50, 60]
Explanation:
- Starts at index
3. - Goes till the end of the list.
4. Using step (skip values):
print(numbers[::2])
Output:
[10, 30, 50]
Explanation:
start&stopare omitted, so covers entire list.step = 2so takes every 2nd element.
5. Full example with start, stop, and step:
print(numbers[1:5:2])
Output:
[20, 40]
Explanation:
start = 1, so starts from index 1 (20).stop = 5, so goes up to index 4 (40), does not include index5(50).step = 2, so takes every 2nd element (skips one each time).
6. Using negative step (reverse slicing):
print(numbers[::-1])
Output:
[60, 50, 40, 30, 20, 10]
Explanation:
step = -1means go backwards in the list.- It starts from the last element and moves towards the first.
- So,
numbers[::-1]gives the list in reverse order.
Summary od slicing:
- Slicing uses
start:stop:step. - If
startis empty, it starts from 0. - If
stopis empty, it goes till end. - If
stepis empty, it takes every item (step=1). - Slicing never includes the
stopindex.