Python lists are ordered collections that allow elements to be accessed using their positions. We can retrieve individual elements using indexing, access multiple elements using slicing, or traverse the entire list using loops.
Example: Consider a list:
a = [10, 20, 30, 40, 50]
print(a[0])
print(a[2])
Output
10 30
Explanation:
- a[0] returns the first element, while a[2] returns the third element.
- Accessing an index outside the valid range raises an IndexError.
1. Using Negative Indexing
Negative Indexing allows us to access elements starting from the end of a list. The last element has index -1, the second-last has index -2, and so on.
Example:
a = [10, 20, 30, 40, 50]
print(a[-1])
print(a[-3])
Output
50 30
Explanation:
- a[-1] accesses the last element, while a[-3] accesses the third-last element.
- Negative indexing is useful when accessing elements from the end without calculating the list length.
2. Using List Comprehension
List comprehension is a more advanced and efficient way to access list items. It allows us to create a new list based on an existing list by applying a condition or transformation.
a = [10, 20, 30, 40, 50]
# Create a new list with items greater than 20
b = [item for item in a if item > 20]
print(b)
Output
[30, 40, 50]
3. Using List Slicing
Slicing is another way to access multiple items from a list. We can get a range of items by specifying a starting index and an ending index. The starting index is included, but the ending index is not.
a = [10, 20, 30, 40, 50]
print(a[1:4])
print(a[:3])
print(a[2:])
Output
[20, 30, 40] [10, 20, 30] [30, 40, 50]
Explanation:
- start specifies the beginning index, while end specifies the stopping position, which is excluded.
- step determines the interval between selected elements. Omitting it uses a default value of 1.
4. Using Loop
A for loop can access every element in a list sequentially without explicitly specifying its index.
Example:
a = [10, 20, 30, 40, 50]
for item in a:
print(item)
Output
10 20 30 40 50
Explanation:
- Loop retrieves each element from the list and assigns it to item.
- Approach is useful when processing or displaying all elements.
5. Using enumerate()
enumerate() function allows us to access both the index and the corresponding element while iterating through a list.
Example:
a = [10, 20, 30]
for index, item in enumerate(a):
print(index, item)
Output
0 10 1 20 2 30
Explanation:
- enumerate() generates index-element pairs, starting from index 0 by default.
- It is useful when a program needs both the position and value of each element.
Accessing Items in Nested List
It contains other lists as elements. We can use multiple indices to access an element inside an inner list.
Example:
a = [[10, 20], [30, 40], [50, 60]]
print(a[1][0])
print(a[2][1])
Output
30 60
Explanation:
- First index specifies the inner list, while the second specifies the element within it.
- a[1][0] accesses the first element of the second inner list.
Handling IndexError While Accessing List Items
It occurs when an index is outside the valid range of a list. For example, accessing a[5] in a list containing only three elements raises this error.
Example:
a = [10, 20, 30]
try:
print(a[5])
except IndexError:
print("Index out of range")
Output
Index out of range
Explanation:
- try block attempts to access an invalid index.
- Except block handles the IndexError and displays a message instead of terminating the program.