📊 We use cookies & analytics to improve your experience. Learn more
Latest

Python for Absolute Beginners Module 2 · Lesson 6 of 15

0% Exit to course

Module 2 · Making the program decide Lesson 6 of 15

Lists — one name, many values

Learning objective

A list holds an ordered set of values: marks = [72, 88, 65]. Indexing starts at 0, and slicing gets a piece: marks[0:2] is the first two.

The concept

A list keeps several values in order under one name: marks = [72, 88, 65]. Position one is written marks[0], because counting starts at zero, and a slice gets a piece: marks[0:2] is the first two values. len(), sum(), sorted(), append() and remove() cover almost everything a first job asks for.

What makes a list powerful is that the computer does the repetitive work: sum(marks) / len(marks) is the average in one line, and it still works when the list has ten thousand values instead of three. Looping over a list — for mark in marks: — is the pattern behind every marksheet, attendance sheet and report you will ever write.

Python
marks = [72, 88, 65, 90]

print(marks[0])               # 72 — counting starts at 0
print(marks[0:2])             # [72, 88]
print(max(marks), min(marks), round(sum(marks) / len(marks), 1))

marks.append(77)              # add one
marks.sort(reverse=True)      # highest first
print(marks)

Common mistakes

The mistakes are small and constant: using marks[1] when you meant the second value and getting the first, trying to sum() a list of text because the numbers came from an input file, and editing a list while looping over it. Convert first with [int(x) for x in marks], then calculate.

Worked example

sum(marks) / len(marks) gives the average in one line — the same three lines of manual addition a beginner usually writes first.

Your practice task

Store ten marks in a list and print the highest, the lowest and the average without writing a single if statement by hand.

Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.

Key takeaway

A list keeps several values in order under one name: marks = [72, 88, 65].

Create free account or sign in

Almost there

15 lessons left of 15

Finish every lesson to unlock the certificate. Each one ends in a practice task — do them and the final project brief writes itself.