List basics · Python from Zero
How do you keep many values together under one name?
Course contentsWhy you need it
Ten test scores in ten variables (s1, s2 ...) is clumsy, and you can't loop over them. A list stores any number of values in order, can grow, and works perfectly with for. Lists are the most used data structure in Python.
The intuition
A list is like a numbered shopping list:
fruits = ["apple", "banana", "cherry"]- Indexing works like strings:
fruits[0]is "apple",fruits[-1]is "cherry". len(fruits)is 3.- Unlike strings, lists can change:
fruits[1] = "blueberry"replaces an item, andfruits.append("date")adds one at the end. for f in fruits:visits each item in order.
To build a list step by step, start empty ([]) and append inside a loop.
Definition
List
A list is an ordered, changeable collection of values written in square brackets, such as [1, 2, 3].
append()
list.append(x) adds the item x to the end of the list.
Examples
A fruit list
Try it yourselfLists print with brackets and quotes.
fruits = ["apple", "banana", "cherry"]
print(fruits[0], len(fruits))
fruits.append("date")
fruits[1] = "blueberry"
print(fruits)
for f in fruits:
print(f.upper())- L2First item and the length.
apple 3 - L3append adds "date" at the end.
4 items - L4Replace the item at index 1.
- L5The whole list.
['apple', 'blueberry', 'cherry', 'date'] - L7The loop visits each item in order.
APPLE ...
Building a list from input
Try it yourselfStart with [] and append in a loop.
n = int(input())
scores = []
for i in range(n):
scores.append(int(input()))
print(scores)3 70 85 90
- L1How many scores: 3.
n = 3 - L2An empty list.
scores = [] - L4Each round reads a number and appends it.
[70] → [70, 85] → [70, 85, 90] - L5Print the finished list.
[70, 85, 90]
Common mistakes
Index out of range
A list of 3 items has indexes 0, 1, 2. items[3] is an IndexError.
append returns nothing
items = items.append(4) sets items to None. Just write items.append(4).
Quick quiz
1. What does this print?
a = [3, 1, 2]
a.append(5)
print(a[-1], len(a))Show the answer
Answer: A
5 was added at the end, so it's the last item, and there are now 4 items.
2. What does this print?
nums = [1, 2, 3]
nums[1] = 20
print(nums)Show the answer
Answer: A
Index 1 is the second item.
Practice
3 exercises in three steps: predict what a program prints, change a program to meet a new requirement, then write one from scratch. Your code runs in the browser and is checked the moment you submit.
- PredictChange and grow
Type exactly what this program prints.
- ModifyCount the big ones
Instead of the sum, count how many numbers in the list are greater than 10. Store it in
countand print it. - WriteCollect the numbers
Read a whole number n, then read n more numbers, one per line. Store them in a list, then print the list and, on the next line, their sum.
Practise this lesson
Open the interactive lesson to edit and run these examples and solve the exercises with instant feedback. Free to start, no sign-up.
Interactive lessons open in order. If you have not done the earlier ones yet, you start at the course map.
Terms in this lesson
| Term | Chinese | Definition |
|---|---|---|
| List | 列表 | An ordered, changeable collection of values in square brackets. |
| Element | 元素 | One item stored in a list. |
| append() | append() 追加 | A list method that adds an item to the end. |
| IndexError | 下标越界错误 | The error raised when an index is outside the valid range. |