Lists
Objectives
- Define what a list is in Python and explain its usefulness in storing and managing collections of data.
- Demonstrate how to create lists in Python, including examples of empty lists and lists containing various data types.
- Explain the concept of indexing in Python lists and understand 0-based indexing.
- Retrieve elements from a list using positive and negative indices.
- Understand the use of a for loop to iterate over the elements of a list.
- Introduce list operations like
append()
,insert()
,remove()
, andclear()
. - Use the
in
keyword to check if an item is present in a list. - Employ the
index()
method to get the position of an item in a list.
Consider we need a program that processes capital cities of the world, we could store the names of these cities:
Of course, the problem here is the # etc...
. For each new city we need a new variable.
Lists provide the solution, we can gather together the collection of cities under the one name:
The list is a fundamental data structure in Python that allows us to store and manage such collections of data. The capital_cities
list contains a list of strings, but the list can contain any type of data. Their contents can be changed during the run of the program, items can be added, changed or removed i.e. they are mutable.
Example 8
Predict what the output of the program will be:
- What will the list look like after appending 'orange', line 5?
- Can you identify the data types of the items in
mixed_list
, line 9? - What will be printed on line 12
- What will be printed for
nested_list
, line 15?
Run the program in a Python environment and check your predictions, were they the same?
Creating Lists
To create a list we give it a name followed by the assignment operator and then a comma-separated sequence of items within square brackets []
.
Note
mixed_list
has items of mixed data types, this is allowed, it can also contains lists as in nested_list
. The nested list here, ['a','b']
still counts as one item in this list, the number of elements in nested
is 5.
Accessing Items in a list
Individual elements of the list can be accessed by using indexing. Python uses 0-based indexing, so the first element is at index 0.
To retrieve "Cherry" from the list of fruits we would use:
Warning
Make sure you understand why the index used here is 2 and not 3
Thinks of this processing as mapping where each index "maps" to an item in the list. Any integer expression can be used as the index e.g.
The index can also be negative, in which case it starts to count from the end of the list.Iterating over a list
The easiest way to iterate over the list (visit every item) is to use a for
loop:
This is fine when we need to do something with every item in the list. If we want to modify particular items then we have to use the index for that item, usually combined with a function such as range()
or len()
:
Remember, len()
returns the number of items in the list, and range()
handles the indices from \(0\) to \(n-1\) (where \(n\) is the number of items in the list).
Modifying Lists
- Lists are 'mutable', so you can change their content by assigning new values to elements.
- This can be done by using the index:
List Slicing
- You can extract a portion of a list using slicing, which involves specifying a start and end index, separated by the slice operator, a colon
:
:
Hint
The same slicing approach can be used when extracting sections of a string as a sub-string
- If the first index in the slice is omitted, the slice starts at the beginning of the list; if the second is omitted it will go through to the end of the list. (Omitting both returns the whole list.)
List Operations
There are a number of useful operations, we can perform on the list, including appending, extending, and removing elements.
Most of these list operations act on the list but return None
, e.g. it looks like b
will be assigned the sorted list a
but it does not:
Lists can be joined together, concatenated, using the +
operator:
Note
Similarly the multiplication operator, *
, can be used to repeat the list a number of times in a new list
List Functions
Also, Python provides built-in functions for working with lists, such as len()
, max()
, and min()
.
Checking for List Membership
- You can check if an item is present in a list using the
in
keyword.
- To get the position of an item in a list we use the
index()
method:
Lists and strings
A string is a sequence of characters and often behaves like a list but note the following code:
The list()
function breaks the string into its individual characters.
Example
Activity
Modify the example code to:
- Insert a new fruit into the second position of the
fruits
list. - Remove an element from the
mixed_list
. - Add a new element to one of the sublists in the
nested_list
.
Climate Quest Project
Throughout this topic we'll be working on a large scale project: Climate Quest. In this project a player embarks on a journey to combat the effects of climate change by making decisions that impact the environment. Each choice affects the outcome of the game, emphasizing the importance of individual actions in addressing climate change.
Summary
- Lists are ordered, meaning they maintain the order in which items were added.
- Lists can contain elements of different types.
- Lists are versatile and can be used to implement various data structures like stacks and queues.
- Lists can be nested, meaning you can have lists within lists.
Questions
Programming Tasks
For each of the following tasks write a program using Python.
Write a Python program that allows a user to create and manage a shopping list. Implement features to add, remove, and display items in the list.
Write a Python program that keeps track of student grades. Implement a list to store student names and another list to store their corresponding grades. Allow the user to add and remove students and their grades, and calculate the average grade.
Write a Python program that simulates a to-do list. Allow the user to add, remove, and display tasks in the list. Include an option to mark tasks as completed. The list will be a list of lists where each item in the list will contain a string for the to-do item and a boolean variable for whether the task has been completed or not e.g. `to-do = [['Finish questions for homework', False],['Make the supper', True']]`. Use the following code as your starting point:
-
[https://ehmatthes.github.io/pcc_3e/cheat_sheets/(https://ehmatthes.github.io/pcc_3e/cheat_sheets/)] ↩