Access List Items in Python
How to Access List Items
In Python, lists are data structures that allow you to store multiple items in a single variable. This lesson will cover various methods to access list items, including positive and negative indexing, ranges of indexes, and checking for the existence of items.
1. Access List Items
List items are indexed, meaning you can access them by referring to their index number. Python uses zero-based indexing, which means the first item has an index of 0
.
Example:
To print the second item of a list:
python
1thislist = ["apple", "banana", "cherry"]
2print(thislist[1]) # Output: banana
2. Negative Indexing
Negative indexing allows you to access list items from the end of the list. In this case, -1
refers to the last item, -2
refers to the second last item, and so on.
Example:
To print the last item of the list:
python
1thislist = ["apple", "banana", "cherry"]
2print(thislist[-1]) # Output: cherry
3. Range of Indexes
You can specify a range of indexes to access multiple items from a list. When you specify a range, the return value will be a new list containing the specified items.
Example:
To return the third, fourth, and fifth items:
python
1thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
2print(thislist[2:5]) # Output: ['cherry', 'orange', 'kiwi']
Note: The search starts at index 2
(included) and ends at index 5
(not included).
Leaving Out the Start Value
If you leave out the start value, the range will start from the beginning of the list.
Example:
To return items from the beginning to, but not including, "kiwi":
python
1thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
2print(thislist[:4]) # Output: ['apple', 'banana', 'cherry', 'orange']
Leaving Out the End Value
If you leave out the end value, the range will go on to the end of the list.
Example:
To return items from "cherry" to the end:
python
1thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
2print(thislist[2:]) # Output: ['cherry', 'orange', 'kiwi', 'melon', 'mango']
4. Range of Negative Indexes
You can also specify negative indexes to start the search from the end of the list.
Example:
To return items from "orange" (-4) to, but not including "mango" (-1):
python
1thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
2print(thislist[-4:-1]) # Output: ['orange', 'kiwi', 'melon']
5. Checking if an Item Exists
To determine if a specific item is present in a list, you can use the in
keyword. This will return True
if the item exists and False
otherwise.
Example:
To check if "apple" is present in the list:
python
1thislist = ["apple", "banana", "cherry"]
2if "apple" in thislist:
3 print("Yes, 'apple' is in the fruits list") # Output: Yes, 'apple' is in the fruits list