Access List Items
What You'll Learn: In this tutorial, you'll discover how to access items in a list using their index numbers. A list is like a sequence of items that you can refer to by their position.
Accessing Items by Index
List items are indexed, and you can access them by referring to their index number. Remember, the first item has an index of 0.
Example Code:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Output: banana
What's Happening Here?
thislist[1]accesses the second item in the list.
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 Code:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Output: cherry
What's Happening Here?
thislist[-1]accesses the last item in the list.
Range of Indexes
You can specify a range of indexes to return a sublist. The range starts from the first index (included) to the second index (not included).
Example Code:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Output: ['cherry', 'orange', 'kiwi']
What's Happening Here?
thislist[2:5]accesses the third, fourth, and fifth items.
Range from Start
By leaving out the start index, the range starts at the first item.
Example Code:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
Output: ['apple', 'banana', 'cherry', 'orange']
Range to End
By leaving out the end index, the range goes to the end of the list.
Example Code:
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 Code:
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 Code:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Output: Yes, 'apple' is in the fruits list
Try It Yourself: Fun Exercises
- Find Your Favorite Fruit:
- Create a list of fruits.
- Access your favorite fruit using its index.
- Check for a Snack:
- Create a list of snacks.
- Use the
inkeyword to check if a specific snack is in the list.
Summary:
In this Python tutorial, we learned how to access items in a list using their index numbers, including negative indexing and ranges. We also learned how to check if an item exists in a list. Lists are a great way to store and access multiple items efficiently. Keep experimenting and have fun with lists in Python!