Creating and reading a list
fruits = ["apple", "mango", "kiwi"]
print(fruits[0]) # apple
print(fruits[-1]) # kiwi
print(len(fruits)) # 3Positions start at 0. A negative index counts from the end.
Changing a list
fruits.append("grape")adds to the end.fruits.remove("mango")removes the first match.fruits[1] = "banana"replaces an item.
Looping over a list
nums = [4, 7, 2]
total = 0
for x in nums:
total = total + x
print(total) # 13Common beginner mistakes
- Using
fruits[3]on a 3-item list — the last index is 2. - Writing
fruits = fruits.append(x), which sets the list toNone.
Practice exercises
Try each one yourself first, then open it in the Visualizer to watch every line run.
Exercise 1
Shopping list
Start with an empty list, add three items, remove one, and print the list and its length.
items = []
# append, append, append, removeHint
Use items.append("milk") and items.remove("milk").
Show solution and explanation
items = []
items.append("milk")
items.append("bread")
items.append("eggs")
items.remove("bread")
print(items, len(items))Watch the list grow box by box in memory, then shrink. remove deletes the first matching item and later items slide left.
Watch the solution step by stepExercise 2
Average marks
Work out the average of a list of marks.
marks = [70, 85, 60, 90]
# total, then divideHint
Loop to add them up, then divide by len(marks).
Show solution and explanation
marks = [70, 85, 60, 90]
total = 0
for m in marks:
total = total + m
print(total / len(marks)) # 76.25total grows each round; dividing by the number of items gives the average. / always gives a decimal answer.
Watch the solution step by stepExercise 3
Only the evens
Build a new list containing only the even numbers.
nums = [3, 8, 5, 12, 7, 4]
evens = []
# loop and appendHint
Append x when x % 2 == 0.
Show solution and explanation
nums = [3, 8, 5, 12, 7, 4]
evens = []
for x in nums:
if x % 2 == 0:
evens.append(x)
print(evens) # [8, 12, 4]The original list is untouched; the new list only receives items that pass the test.
Watch the solution step by step