Access Items
Every list item has an index number, and that number is how you reach it:
Note: Indexes begin at 0, so that is where the first item sits.
Example
Index 1 gives us the second item:
Output: complete Python program
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Negative Indexing
A negative index counts backward from the end of the list.
So -1 is the final item, -2 is the one just before it, and so on.
Example
Get the final item and print it:
Output: complete Python program
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Range of Indexes
To get several items at once, give a start and an end for the range.
The result comes back as a new list holding just those items.
Note: In the first example, the range begins at index 2, which is included, and stops at index 5, which is left out. Keep in mind that counting begins at 0.
Example
Get the items in third, fourth and fifth position:
Output: complete Python program
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Example
Leave out the start and the range begins at the first item, stopping just before "kiwi":
Output: complete Python program
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
Example
Leave out the end and the range runs from "cherry" through the last item:
Output: complete Python program
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
Range of Negative Indexes
A range can also use negative indexes, which count back from the end of the list:
Example
The range covers "orange" (-4) up to "mango" (-1), but "mango" itself is left out:
Output: complete Python program
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
Check if Item Exists
The in keyword tells you whether a given item is in a list:
Example
Test whether the list contains "apple":
Output: complete Python program
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")