Python List Index: Get and Change Items
Get an Item by Its Index
Every item in a list has a position number, called its index. To get one item, write the list's name and the index in square brackets: friends[0].
Think of the floors in a building where the ground floor is floor 0. The first floor you reach is 0, the next one is 1, and so on.
friends = ["Sunny", "Rocky", "Lucky"]
print(friends[0])
print(friends[1])
print(friends[2])Sunny Rocky Lucky
| Item | "Sunny" | "Rocky" | "Lucky" |
|---|---|---|---|
| Index | 0 | 1 | 2 |
The rules
- The first item has index 0, not 1.
- The last item has index
len(list) - 1. Three items means indexes 0, 1 and 2. - The index is a whole number.
friends[1.0]gives aTypeError.
Why start at 0? Read the index as "how many steps from the start". The first item is 0 steps away, the second is 1 step away.
Use an item like any value
prices[0] is a value, just like a variable. You can print it, store it, or calculate with it:
prices = [40, 25, 60]
total = prices[0] + prices[2]
print(f"Total: {total}")Total: 100
Common beginner doubt: which one is the second item?
friends[1] is the second item, "Rocky". Every beginner reaches for friends[1] when they want the first item. If your program shows the wrong item, check whether you started counting at 0.
The index counts from 0:
list[0]is the first item,list[1]the second.