Indexing and Slicing in Python Lists Read
Indexing and Slicing in Python Lists Read
Indexing and slicing are fundamental operations to access and extract elements from a list in Python.
1. Indexing (Accessing Single Elements)
- Lists are zero-indexed (first element is at index
0). - Negative indices count from the end (
-1= last element).
Example 1: Basic Indexing
python
fruits = ["apple", "banana", "cherry", "date", "fig"] # Positive indexing print(fruits[0]) # "apple" (1st element) print(fruits[2]) # "cherry" (3rd element) # Negative indexing print(fruits[-1]) # "fig" (last element) print(fruits[-3]) # "cherry" (3rd from the end)
Output:
text
apple cherry fig cherry
2. Slicing (Extracting a Sub-List)
- Syntax:
list[start:stop:step]start(inclusive),stop(exclusive),step(optional, default=1).
- Omitting
startorstopslices from the start/end.
Example 2: Basic Slicing
python
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Get elements from index 2 to 5 (exclusive) print(numbers[2:5]) # [2, 3, 4] # From start to index 4 print(numbers[:4]) # [0, 1, 2, 3] # From index 6 to end print(numbers[6:]) # [6, 7, 8, 9] # Every 2nd element print(numbers[::2]) # [0, 2, 4, 6, 8] # Reverse the list print(numbers[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Output:
text
[2, 3, 4] [0, 1, 2, 3] [6, 7, 8, 9] [0, 2, 4, 6, 8] [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]