Lesson explanation
After this lesson, you will be able to:
len() to count elements and understand valid index boundaries.Python lists hold ordered values in square brackets. If you know arrays from JavaScript or Java, the idea is familiar—but Python lists can grow and can contain different kinds of values. We will focus on simple lists of related values here.
services = ["api", "worker", "database"]An index starts at 0, so services[0] is the first value. Negative indexes count from the end: services[-1] is the last value, regardless of list length.
Lists are mutable: assigning to an existing position changes that element. The assignment must use a valid index. For a list with three elements, the positive indexes are 0, 1, and 2; 3 is out of range.
Use len(services) to find the number of elements. The last positive index of a non-empty list is len(services) - 1. An empty list has length zero and no first or last element.
A list literal preserves the order of its elements.
queue_names = ["urgent", "normal", "low"]
print(queue_names[0])
print(queue_names[2])Output:
urgent
lowThe first position is 0, not 1.
Negative indexing avoids assuming a fixed list length.
releases = ["v1.2", "v1.3", "v1.4"]
print(releases[-1])
print(releases[-2])Output:
v1.4
v1.3The -1 index is the last item; -2 is the one before it.
Changing a list element does not require creating a new list.
channels = ["dev", "test", "prod"]
channels[1] = "staging"
print(channels)Output:
['dev', 'staging', 'prod']Only the item at index 1 changes.
len() counts values, not the last index.
active_regions = ["eu", "us"]
count = len(active_regions)
print(f"Regions: {count}")
print(f"Last positive index: {count - 1}")Output:
Regions: 2
Last positive index: 1| Goal | Python |
|---|---|
| Create a list | items = ["a", "b"] |
| Read first element | items[0] |
| Read last element | items[-1] |
| Update an element | items[0] = "new" |
| Count elements | len(items) |
| Last positive index (non-empty list) | len(items) - 1 |
1: Python lists are zero-based.items[len(items)]: that position is beyond the last element; use -1 or len(items) - 1 for a non-empty list.IndexError.items[1] = value replaces an existing item; it does not insert a new one.