livepython.net
CHAPTER 09Python Lists
9.2  INDEXING

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.

PYTHONedit me
friends = ["Sunny", "Rocky", "Lucky"]
print(friends[0])
print(friends[1])
print(friends[2])
OUTPUT
Sunny
Rocky
Lucky
Item"Sunny""Rocky""Lucky"
Index012

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 a TypeError.

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:

PYTHONedit me
prices = [40, 25, 60]
total = prices[0] + prices[2]
print(f"Total: {total}")
OUTPUT
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.

your turnPredict the output

What will this print?

colors = ["red", "green", "blue"] print(colors[1])
Your turn! What will this code show on the screen?
your turnFill the gap

Print the first day

days = ["Mon", "Tue", "Wed"] print(days[?])

It should print: Mon

Which piece makes this code work?

Negative Index: Count from the End

A negative index counts from the end of the list. -1 is the last item, -2 is the one before it, and so on.

Think of a queue at a shop. You can say "the last person in the queue" without counting everyone from the front.

PYTHONedit me
friends = ["Sunny", "Rocky", "Lucky"]
print(friends[-1])
print(friends[-2])
print(friends[-3])
OUTPUT
Lucky
Rocky
Sunny

Every item has two indexes, one from the front and one from the back:

Item"Sunny""Rocky""Lucky"
Index012
Negative index-3-2-1

The rules

  • -1 is always the last item, whatever the length of the list.
  • There is no "minus zero". -0 is the same as 0, the first item.
  • The first item is at -len(list): -3 in a list of three.

Why it's handy

You often want the newest item, and the newest item is usually at the end. A negative index gets it without knowing the length:

PYTHONedit me
scores = [12, 45, 33, 27, 50]
print("Latest score:", scores[-1])
print("Same item:", scores[len(scores) - 1])
OUTPUT
Latest score: 50
Same item: 50

Good: scores[-1]. Short and clear.

Avoid: scores[len(scores) - 1]. It works, but it's longer and easy to get wrong. Forget the - 1, and you get an error (next lesson).

-1 is the last item and -2 the one before it. Negative indexes count from the end.

your turnType the output

Type what this prints

nums = [10, 20, 30, 40] print(nums[-2])
Read the code line by line, then type the output exactly.
your turnPick the right idea

Which one always gives the last item of a list called items?

Think about it, then pick one.

IndexError: list index out of range

Ask for an index that the list doesn't have, and Python stops with an IndexError.

Think of a lift in a three-floor building. Press the button for floor 5, and nothing can take you there: that floor doesn't exist.

PYTHONedit me
friends = ["Sunny", "Rocky", "Lucky"]
print(friends[3])
OUTPUT
IndexError: list index out of range

Don't be scared of this error! It's just saying: "this index is outside the list". The list has three items, so the indexes go from 0 to 2. There is no index 3.

The rules

  • A list of length n has indexes 0 to n - 1.
  • From the back, it has -1 to -n.
  • Anything outside that range is an IndexError.

The most common cause

Using len() as the index. len(friends) is 3, but the last index is 2:

PYTHONedit me
friends = ["Sunny", "Rocky", "Lucky"]
print(friends[len(friends)])
OUTPUT
IndexError: list index out of range

Every error is a clue! When you see IndexError, print the list and its length, then compare them with the index you used.

Check the index first

When the index comes from the user, you can't know it in advance. Check it with an if from chapter 8 before you use it:

PYTHONedit me
friends = ["Sunny", "Rocky", "Lucky"]
n = int(input())
if 0 <= n < len(friends):
    print(friends[n])
else:
    print("No friend at that index")
OUTPUT
No friend at that index

Try 0, 2 and 3 in the Input box. Only 0, 1 and 2 pass the check.

Valid indexes go from 0 to len(list) - 1. Anything else is an IndexError.

your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.

Change an Item in a List

You can change an item in a list: put the index on the left of =, and the new value on the right. Lists that can be changed like this are called mutable (a fancy word for "changeable").

Think of a timetable on a whiteboard. Rub out one lesson and write another in its place. The rest of the week stays the same.

PYTHONedit me
menu = ["tea", "coffee", "juice"]
menu[1] = "lassi"
print(menu)
OUTPUT
['tea', 'lassi', 'juice']

The rules

  • list[index] = value replaces the item at that index. It's reassignment from chapter 4, for one item.
  • The other items don't move.
  • Negative indexes work too: menu[-1] = "water" changes the last item.
  • The index must already exist. This can change items, but it can't add new ones.

Change an item using its own value

Like score = score + 5 in chapter 4, an item can get a new value worked out from its old one. Even += from chapter 5 works:

PYTHONedit me
scores = [10, 20, 30]
scores[0] = scores[0] + 5
scores[-1] += 1
print(scores)
OUTPUT
[15, 20, 31]

Avoid: an index that isn't there

PYTHONedit me
menu = ["tea", "coffee"]
menu[2] = "juice"
OUTPUT
IndexError: list assignment index out of range

The list has indexes 0 and 1. Index 2 doesn't exist yet, so Python can't put anything there. To add a new item at the end, use append() from topic 4.

Change an item with list[index] = value. The index must already exist.

your turnOrder the lines

Put the lines in order to print [55, 60, 75]

  1. marks[-1] = marks[0] + 20
  2. marks = [50, 60, 70]
  3. print(marks)
  4. marks[0] = 55
These lines are mixed up. Put them back in order, then press Check.
your turnPredict the output

What will this print?

x = 7 if x % 2 == 0: print("even") else: print("odd")
Your turn! What will this code show on the screen?

Practice: Indexing

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 72.Python Program to Print the First and Last Item of a ListEasySolve
  2. 73.Python Program to Find the Day Name from Its NumberMediumSolve