Python – Access List Items
Accessing elements from a list in Python is straightforward. Lists are ordered, and each item has an index starting from 0
.
Accessing Items Using Index
You can use the index number to access specific items in a list.
Example:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # First item
print(fruits[1]) # Second item
Output:
apple
banana
Negative Indexing
Negative indexing allows you to access items from the end of the list.
fruits = ["apple", "banana", "cherry"]
print(fruits[-1]) # Last item
print(fruits[-2]) # Second last item
Output:
cherry
banana
Range of Indexes (Slicing)
You can access a range of items using list slicing.
list[start_index : end_index]
Syntax:
list[start_index : end_index]
Note: The end index is excluded.
Example:
fruits = ["apple", "banana", "cherry", "orange", "kiwi"]
print(fruits[1:4])
Output:
['banana', 'cherry', 'orange']
Omitting Start or End Index
Example:
# From beginning to index 3 (excluding 3)
print(fruits[:3])
# From index 2 to the end
print(fruits[2:])
Output:
['apple', 'banana', 'cherry']
['cherry', 'orange', 'kiwi']
Range with Negative Indexes
You can combine slicing with negative indexes.
Example:
print(fruits[-4:-1])
Output:
['banana', 'cherry', 'orange']
Using a Loop to Access Items
You can also iterate through a list using a for
loop:
Example:
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
orange
kiwi
Summary
- Use
list[index]
to access a single item. - Use negative indexes to access items from the end.
- Use slicing
list[start:end]
to get a sublist. - Python lists start at index
0
.