Indexing, Membership, and Length
In this tutorial, we'll access items, check membership, and count values.
Many collections share common operations. Three of the most useful are indexing, membership, and length.
Indexing
Indexing gets an item by position. Lists, strings, and tuples support indexing.
names = ["Ada", "Grace", "Linus"]
print(names[0])
print(names[2])
Output:
Ada
Linus
Python starts counting at 0.
Negative indexes count from the end:
print(names[-1])
Output:
Linus
Membership
Membership checks whether a value is inside something. Use in.
names = ["Ada", "Grace", "Linus"]
print("Ada" in names)
print("Sam" in names)
Output:
True
False
This also works with strings:
print("py" in "python")
And dictionaries check keys:
student = {"name": "Ada", "score": 95}
print("score" in student)
Length
len() counts how many items there are:
print(len(names))
print(len("python"))
Output:
3
6
Common Mistake
The last index is always one less than the length:
names = ["Ada", "Grace", "Linus"]
print(len(names)) # 3
print(names[3]) # error
The valid indexes are 0, 1, and 2.
Putting Them Together
You can combine these ideas:
names = ["Ada", "Grace", "Linus"]
if len(names) > 0:
print("First name:", names[0])
if "Grace" in names:
print("Grace is in the list")
This checks the collection before using it, which makes your code easier to reason about.
Practice
Create a list of four cities. Print the first city, check if a city is in the list, and print the length.