Beginner Chapter 41 · 20 min read · Module 4: Python Data Structures
List Creation and Indexing
- After this chapter you can create lists with brackets, list(), range() and repetition.
- You can read items with positive and negative indexes.
- You can explain and avoid IndexError.
- You can read items from a nested list using two indexes.
- You can find the position of an item with index() and count matching items.
You already know that a list holds many values in order. This chapter looks closely at two basic skills: creating lists in several ways, and reaching exactly the item you want by its index. Together these skills make up most of everyday list work.
Python gives you more than one way to make a list. You can type the items by hand, convert another sequence with the list() function, produce a run of numbers with range(), or repeat a small list with the multiplication sign. Each way is useful in different situations.
Indexing needs careful attention because it starts at zero and also allows negative numbers. A small mistake here causes the very common IndexError. By the end of this chapter you will be able to predict which item any index points to, even in a list inside another list.
Ways to create a list
The simplest way is a list literal: the items are written between square brackets. You can also call list() with any sequence, such as a string or a range, and Python will put each element in a new list. The function range(5) makes the numbers 0 to 4, but it does not print as a list, so wrap it with list() to see the values.
a = [3, 6, 9]
b = list("hey")
c = list(range(5))
d = [0] * 4
print(a)
print(b)
print(c)
print(d)The expression [0] * 4 repeats the list contents four times, which is handy to make a starting list filled with zeros. You can also join lists using +, which creates a new list that has the items of both.
left = [1, 2]
right = [3, 4]
print(left + right)
print(left * 3)
print(left)Positive indexing
If a list has n items, the valid positive indexes are 0 to n - 1. The expression items[0] is the first item and items[n - 1] is the last. Picture the list as a row of boxes numbered from zero. The number is the distance from the start, which is why the first box has distance zero.
Negative indexing
Negative indexes count from the end. The last item is -1, the second to last is -2, and so on. For a list of n items the valid negative indexes are -1 down to -n. Negative indexes are very useful because you do not need to know the length of the list to reach the last items.
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
print(days[0], days[4])
print(days[-1], days[-5])
print(days[len(days) - 2])| Item | Mon | Tue | Wed | Thu | Fri |
|---|---|---|---|---|---|
| Positive index | 0 | 1 | 2 | 3 | 4 |
| Negative index | -5 | -4 | -3 | -2 | -1 |
IndexError
When the index is outside the valid range, Python stops with an IndexError: list index out of range. This happens for days[5] and for days[-6] in the list above. It also happens on an empty list, even for index 0. You can guard against it by checking len() first, or by catching the error with try and except.
days = ["Mon", "Tue"]
try:
print(days[2])
except IndexError as err:
print("Problem:", err)
print("Done")Nested lists
A list may contain other lists. This is a simple way to represent a table, such as rows and columns. To reach an inner value, use two indexes: the first picks the row and the second picks the item inside that row. Think of grid[1][2] as: take the list at position 1, then take the item at position 2 of that list.
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(grid[0])
print(grid[1][2])
print(grid[-1][0])
for row in grid:
print(row[0], row[-1])Finding items: index() and count()
If you know the value but not its position, call index(value). It returns the position of the first match, and raises ValueError when the value is missing. The method count(value) tells you how many times the value appears. Use in first if you are not sure that the value is there.
letters = ["a", "b", "c", "b"]
print(letters.index("b"))
print(letters.count("b"))
print("z" in letters)
if "c" in letters:
print("c is at", letters.index("c"))Python syntax
items = [a, b, c]items = list(iterable)items = [value] * countitems[i] or items[-i]grid[row][column]items.index(value)Real-world applications
- Reading the first and last records of data.
- Representing a game board or spreadsheet with nested lists.
- Creating a list of zeros for counters before a loop starts.
- Converting a string to a list of characters for processing.
Common mistakes
Fix: Use items[len(items) - 1] or simply items[-1].
Fix: The first item is items[0]; the second is items[1].
Fix: Check with the in operator first or catch ValueError.
Fix: That repeats the same inner list. Use a loop or comprehension to make separate rows.
Important tips
- Use negative indexes for items near the end.
- Print len(items) when you are unsure about the valid range.
- Use list(string) to split a word into characters.
- Read nested indexes from left to right: outer list first.
Key points summary
- Lists can be created with [], list(), range() and repetition.
- Valid indexes are 0 to n-1 and -1 to -n.
- An invalid index raises IndexError.
- grid[r][c] reaches inside a nested list.
- index() finds a position and count() counts matches.
Exam and interview points
- items[-1] is the last item.
- IndexError: list index out of range.
- [0] * 3 gives [0, 0, 0].
- list('abc') gives ['a', 'b', 'c'].
- index() raises ValueError if the value is missing.
Quick revision
- First is 0, last is -1.
- Valid range: -n to n-1.
- Nested: grid[row][col].
- index() = position, count() = how many.
- range() needs list() to show values.
Frequently asked questions
Why does indexing start at zero?
The index is the distance from the start of the list. The first item has distance zero. Many programming languages use the same rule.
Does list(range(5)) include 5?
No. range(5) stops before 5, so you get 0, 1, 2, 3, 4.
What is the difference between + and append()?
The + operator makes a new list from two lists. append() adds one item to an existing list and changes it.
Can I use a float as an index?
No. Indexes must be integers. items[1.0] raises a TypeError.
Practise this chapter
19 practice questions Take the chapter quiz