Before you start this course, you must login to Replit
If you have forgotten your Replit account user name or password, ask your Coder Coach.
If you have forgotten your Replit account user name or password, ask your Coder Coach.
At the ‘predict’ & ‘run’ stages students work entirely with example code. They should inspect it carefully and write a prediction about what it will do.
They then run the code and compare the result to their prediction.
A list is an example of a data structure. This is the name for a number of different programming techniques used to organise and manipulate data in programs.
So far to store data in the program we have used variables, which hold one piece of data and use an identifier (variable name) to represent it in the code.
Lists work in the same way as variables, but they can store multiple items of data using one identifier rather than just one.
Lists are created in Python like this:
# List of strings
countries = ["UK", "USA", "Chad", "Australia", "Thailand", "Canada"]
# List of integers
prime_numbers = [1,3,5,7,11,13]
To identify individual items in a list, the data is indexed (given a number). Indexing starts at 0, meaning that the first item in a list will be number 0, the second number 1 and so on.
We can also print an individual item from a list or the entire list using the following syntax:
# This will print 'UK'
print(countries[0])
# This will print 'Canada'
print(countries[5])
# This will print the entire list
print(countries)
We can change items in lists by using the assignment operator (=
) with the index of the item to be changed.
# Changes the first item in the 'countries' list to 'France'
countries[0] = "France"
Here are some other useful methods that can be used with lists
Method Name | What it does | Example Code |
---|---|---|
print() |
Prints the list, or part of the list | Prints every item in the countries list: print(countries) Prints item at index 0 in the countries list: print(countries[0])
|
append() |
Adds an item to the end of the list | countries.append("Japan") |
insert() |
Adds an item at a specific position in the list | countries.insert(0, "France") |
remove() |
Removes a certain item from a list | countries.remove("USA") |
pop() |
Removes the last item of a list | countries.pop() |
Python makes it really easy to check if an item is in a list. This is where we can start to combine what we’ve previously learned about selection with lists. The code for this is:
if "item" in list_name:
# Run this code if condition is true
Make sure that you check for the following things: