Access List Items
Accessing list items is a core concept in Python.
Because lists are ordered, every item has a fixed position (index) that can be used to read data efficiently.
This topic covers basic to advanced ways of accessing list elements.
List Indexing Basics
List items are accessed using index numbers.
Indexing in Python starts from 0.
python
fruits = ["apple", "banana", "cherry"]
print(fruits[0])
python
print(fruits[1])
python
print(fruits[2])
Negative Indexing
Negative indexing allows access from the end of the list.
| Index | Meaning |
|---|---|
-1 | Last item |
-2 | Second last item |
python
colors = ["red", "green", "blue"]
print(colors[-1])
python
print(colors[-2])
python
print(colors[-3])
Accessing a Range of Items (Slicing)
Slicing allows you to access multiple items at once.
Syntax
python
list[start : end]
startis inclusiveendis exclusive
python
numbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:4])
python
print(numbers[:3])
python
print(numbers[3:])
Slicing with Negative Indexes
python
numbers = [0, 1, 2, 3, 4, 5]
print(numbers[-4:-1])
python
print(numbers[-3:])
python
print(numbers[:-2])
Accessing with Step Value
You can control how many items to skip using step.
Syntax
python
list[start : end : step]
python
numbers = [0, 1, 2, 3, 4, 5, 6]
print(numbers[::2])
python
print(numbers[1::2])
python
print(numbers[::-1])
Accessing List Items Using Loop
Using for Loop
python
colors = ["red", "green", "blue"]
for color in colors:
print(color)
Using Index with range()
python
for i in range(len(colors)):
print(colors[i])
Accessing Nested List Items
Lists can contain other lists (nested lists).
python
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[0])
python
print(matrix[1][2])
python
print(matrix[2][0])
Accessing List Items Using Conditions
python
numbers = [10, 20, 30, 40]
if 20 in numbers:
print("20 exists in the list")
python
if numbers[0] > numbers[1]:
print("First is greater")
Accessing Items with Unpacking
You can unpack list values into variables.
python
data = [10, 20, 30]
a, b, c = data
print(a)
print(b)
print(c)
Extended Unpacking
python
numbers = [1, 2, 3, 4, 5]
a, *b, c = numbers
print(a)
print(b)
print(c)
Index Out of Range Error (Important)
Accessing an index that does not exist raises an error.
python
numbers = [1, 2, 3]
# print(numbers[5])
Error:
text
IndexError: list index out of range
Safe Way to Access
python
index = 5
if index < len(numbers):
print(numbers[index])
Common Mistakes
Assuming Index Starts from 1
python
numbers = [10, 20, 30]
print(numbers[1]) # This is second element
Confusing Slicing End Index
python
numbers = [1, 2, 3, 4]
print(numbers[1:3]) # Does NOT include index 3
Summary
- Lists use zero-based indexing
- Negative indexing accesses items from the end
- Slicing returns multiple items
- Step value controls skipping
- Nested lists require multiple indexes
- Accessing invalid index raises
IndexError - Unpacking is a powerful access technique