- Create a list and access its items by index
- Use the methods
append,insert,remove,popandsort - Loop over a list and calculate results with
sum,minandmax
There are 25 students in a class, and you need to remember each one's grade. Twenty-five separate variables — grade1, grade2, grade3…? That is tiring and awkward. In Python you can keep all the grades in one list instead — as many items as you like under a single name.
Creating a list
An ordered collection of values written in square brackets [] and separated by commas. The items can be of any type, and the list itself can be changed after it is created.
Indexes and slices work in lists just as in strings: the first item is [0], the last is [-1], and len() gives the number of items.
fruits = ['apple', 'pomegranate', 'fig', 'grape']
print(fruits)
print(len(fruits))
print(fruits[0], fruits[-1])
print(fruits[1:3])
print('fig' in fruits)▸ Expected output
['apple', 'pomegranate', 'fig', 'grape'] 4 apple grape ['pomegranate', 'fig'] True
Changing a list
Unlike strings, lists are mutable: you can replace an item by its index, add new items or remove them. Lists have methods for this:
| Method | What it does |
|---|---|
append(x) | adds x to the end of the list |
insert(i, x) | puts x at position i |
remove(x) | removes the first item equal to x |
pop() | removes the last item and returns it |
sort() | sorts the list in ascending order |
count(x) | counts how many times x appears |
cart = ['bread', 'milk']
cart.append('cheese')
cart.insert(0, 'tea')
print(cart)
cart.remove('milk')
last = cart.pop()
print('Removed:', last)
cart[0] = 'green tea'
print(cart)▸ Expected output
['tea', 'bread', 'milk', 'cheese'] Removed: cheese ['green tea', 'bread']
Lists and loops
Lists and the for loop are made for each other. There are also ready-made functions for calculations: sum() gives the total, and min() and max() give the smallest and largest items. Aysel works out the average of her grades for the term:
grades = [5, 4, 5, 3, 4, 5]
average = sum(grades) / len(grades)
print('Grades:', grades)
print('Max:', max(grades), 'Min:', min(grades))
print(f'Average: {average:.2f}')
print('Number of fives:', grades.count(5))▸ Expected output
Grades: [5, 4, 5, 3, 4, 5] Max: 5 Min: 3 Average: 4.33 Number of fives: 3
A loop is also handy for building a new list from an old one: create an empty list [] and append the items that match a condition.
scores = [45, 82, 67, 90, 38]
passed = []
for s in scores:
if s >= 50:
passed.append(s)
print(passed)
print(len(passed), 'of', len(scores), 'passed')▸ Expected output
[82, 67, 90] 3 of 5 passed
Sorting, split and join
The sort() method changes the list itself, while the sorted() function returns a new sorted list and leaves the old one untouched. reverse=True gives descending order.
numbers = [42, 7, 19, 3]
print(sorted(numbers))
print(numbers)
numbers.sort(reverse=True)
print(numbers)▸ Expected output
[3, 7, 19, 42] [42, 7, 19, 3] [42, 19, 7, 3]
sort() uses a faster, smarter algorithm, but the idea is the same: items are compared and swapped.Two methods act as a bridge between strings and lists: split() breaks a string into words and returns a list, and join() glues the items of a list into one string.
line = 'Baku Ganja Sumgait Lankaran'
cities = line.split()
print(cities)
print(len(cities))
print(' - '.join(cities))▸ Expected output
['Baku', 'Ganja', 'Sumgait', 'Lankaran'] 4 Baku - Ganja - Sumgait - Lankaran
a = [1, 2, 3]
b = a
b.append(4)
print(a)
c = a.copy()
c.append(5)
print(a, c)▸ Expected output
[1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4, 5]
Print the highest score, the lowest score and the sum of all scores — each on its own line. Use max(), min() and sum().
scores = [72, 95, 88, 61, 90]
# 1) the highest score
# 2) the lowest score
# 3) the sum of all scores▸ Expected output
95 61 406
temps holds the temperatures of one week. Use a loop and append to build a new list hot with the temperatures above 25°, sort it from highest to lowest and print it. Then print the number of hot days.
temps = [22, 31, 27, 19, 33, 25, 29]
hot = []
# 1) append every temperature above 25 to hot
# 2) sort hot from highest to lowest and print it
# 3) print how many hot days there were▸ Expected output
[33, 31, 29, 27] 4
Key points
- A list is an ordered, changeable collection of values in
[]. - Indexes start at 0; an index that does not exist causes an
IndexError. append,insert,removeandpopchange a list;sum,min,maxandlenhelp with calculations.sort()sorts the list itself;sorted()returns a new list.split()turns a string into a list;join()turns a list into a string.
Check yourself
10 questions. Every correct answer earns XP.
nums = [10, 20, 30], what is nums[1]?