Accessing List Items in Python: Indexing and Negative Indexing
Learn how to access items in Python lists using indexing and negative indexing techniques. Discover how to retrieve items by their index number, and understand negative indexing to access list elements from the end. Explore practical examples with code snippets demonstrating how to work with list indices effectively.
Python - Access List Items
Access Items
List items are indexed, and you can access them by referring to their index number:
Example
thislist = ["orange", "grape", "melon"]
print(thislist[1])
Output
grape
Note: The first item has index 0.
Negative Indexing
Negative indexing means starting from the end of the list. -1 refers to the last item, -2 refers to the second last item, and so on.
Example
thislist = ["orange", "grape", "melon"]
print(thislist[-1])
Output
melon
Range of Indexes
You can specify a range of indexes by specifying where to start and end the range. The return value will be a new list with the specified items.
Example
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Output
['cherry', 'orange', 'kiwi']
Note: The search will start at index 2 (included) and end at index 5 (not included).
Omitting Start Value
If you leave out the start value, the range will start at the first item:
Example
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
Output
['apple', 'banana', 'cherry', 'orange']
Omitting End Value
If you leave out the end value, the range will go on to the end of the list:
Example
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
Output
['cherry', 'orange', 'kiwi', 'melon', 'mango']
Range of Negative Indexes
You can specify negative indexes if you want to start the search from the end of the list:
Example
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
Output
['orange', 'kiwi', 'melon']
Check if Item Exists
To determine if a specified item is present in a list, use the in
keyword:
Example
thislist = ["orange", "grape", "melon"]
if "orange" in thislist:
print("Yes, 'orange' is in the fruits list")
Output
Yes, 'orange' is in the fruits list