Lists

Oliver Irwin

10th March 2023

Objectives

  • describe the concept of lists
  • manipulate lists to represent data
  • construct lists from different data fields

Context

Say you are a teacher and you are grading students

You want to store the students’ grade in a variable

If you have one student, it’s easy!

student_grade = 12

Context (foll.)

What happens if you now have 2 students?

student1_grade = 12
student2_grade = 4

Context (end)

Imagine you now have 12 students

student1_grade = 12
student2_grade = 4
...
student12_grade = 18

Seems complicated to handle…

A more complicated variable type

We introduce a new type to handle sets of data

A list is a set of variables grouped into one

l = ["string", "test", "moodle", "rubika"]

List creation

In Python, lists are created like variables

The data has to be enclosed by square brackets [

The elements have to be separated by commas ,

Indexes

Every element in a list has an index

They start at 0

week = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
Item mon tue wed thu fri sat sun
index 0 1 2 3 4 5 6

Accessing an element

To access an element in a list, you use it’s index

print(week[1])
tue

Adding an element

You can add elements to the end of a list

week = ["mon", "tue", "wed", "thu", "fri"]
week.append("sat")
week.append("dim")

Adding mutliple elements

You can add two lists together

week_days = ["mon", "tue", "wed", "thu", "fri"]
week_end = ["sat", "sun"]

week = week_days + week_end

Useful functions

# Add an element
l.append(element)
# Reverse list
l.reverse()
# Get the size of the list
len(l)
# Find out if an element is in a list
element in l
# Return a sorted version of the list
s = sorted(l)
# Get the smallest / biggest element in the list
min(l) / max(l)