Creating lists and indexing
A list stores an ordered collection of values in a single variable. Instead of score1, score2, score3, you keep them all together.
Creating a list
Write the values inside square brackets, separated by commas:
A list can hold numbers, strings, or a mix — and it can be empty.
Indexing: reaching one item
Each item has a position, called its index. Python counts from 0, not 1:
The first item is fruits[0]. This trips up everyone at first — just remember Python starts counting at zero.
Negative indexing: counting from the end
A negative index counts backward from the end. -1 is always the last item:
This is handy when you want the last item but don't know how long the list is.
How many items? len()
len() gives you the number of items in a list:
Because indexing starts at 0, the last valid index is always len(list) - 1. For a 3-item list that's index 2.
Watch out for out-of-range
Asking for an index that doesn't exist raises an error:
There is no fruits[3] — the valid indexes are 0, 1, and 2.
Key takeaways
- A list holds an ordered collection of values:
[1, 2, 3] - Indexing starts at 0 — the first item is
list[0] - Negative indexes count from the end —
list[-1]is the last item len(list)returns how many items the list has- The last valid index is
len(list) - 1; going past it raises anIndexError
No comments yet. Add the first comment to start the discussion.