So far we have learned how to work with text, numbers and conditional statements. Let's move on to how to repeat things in Python.
Ensure that you are signed into GitHub
Open the assignment: Project 5 - To Do List
Clone the repository to your computer using GitHub Desktop, or open it online using Codespaces
Open lab1.py
Before we dive into lists, let's consider a scenario where you need to store the names of several students in a class. Without lists, you might be tempted to create individual variables for each student like this:
But what if your class has 30 students? Or 100? Creating and managing separate variables for each becomes impractical.
This is where Python lists come in handy.
A list in Python is a collection of items that is ordered and changeable.
It allows us to store multiple items in a single variable. Let's rewrite the previous example using a list:
In this list, students, we have stored three names. You can access each item by its index (starting from 0), like students[0] for "Alice".
Often, you'll need to add more items to your list.
Python lists are dynamic, meaning you can add items to them. This is done using the append() method.
Now, students becomes ["Alice", "Bob", "Charlie", "David"].
You can access elements of a list by referring to the index number. This is called indexing.
Remember, lists in Python are zero-indexed, so the first element is at index 0.
Lists are mutable, meaning their elements can be changed.
Here we replace "Alice" with "Alicia" by specifying that the element at index 0 be replaced.
Complete the exercises found in Lab 1 which cover:
Creating a List
Adding Elements to a List
Accessing List Elements
Modifying List Elements
Press Ctrl + F5 to run the program or open a terminal and type python lab1.py
You should now know how to create and use lists in Python.
Let's wrap up this lab by pushing our code to GitHub:
Enter a commit message. E.g. "Lab 1 complete"
Press Commit to main
Press Push origin