8.2 Lists
8.2a What are Python lists?
Python lists are a built-in data structure used to store an ordered collection of items. Lists are mutable, meaning their contents can be changed after creation. They can hold items of any data type, including integers, strings, and even other lists.
8.2b Why do we use lists?
We use lists because they provide a flexible way to organize and manipulate data. Lists allow us to store a collection of items in a single variable, iterate over the items, and perform various operations like adding, removing, or sorting elements. This makes lists an essential tool for managing data in Python programs.
8.2c How do we use lists?
Here are examples demonstrating the use of some common list functions:
Example 8.2.1 - append(item)
- Adds an item to the end of the list.
Example 8.2.1 - Output
['apple', 'banana', 'cherry', 'date']
Example 8.2.2 - clear()
- Removes all items from the list.
Example 8.2.2 - Output
[]
Example 8.2.3 - count(item)
- Returns the number of occurrences of an item in the list.
fruits = ['apple', 'banana', 'cherry', 'banana']
banana_count = fruits.count('banana')
print(banana_count)
Example 8.2.3 - Output
2
Example 8.2.4 - insert(index, item)
- Inserts an item at a specified position in the list.
Example 8.2.4 - Output
['apple', 'blueberry', 'banana', 'cherry']
Example 8.2.5 - len()
- Returns the number of items in the list.
Example 8.2.5 - Output
4
Example 8.2.6 - pop([index])
- Removes and returns the item at the specified index. If no index is specified, it removes and returns the last item.
fruits = ['apple', 'blueberry', 'banana', 'cherry']
last_fruit = fruits.pop()
print(last_fruit)
print(fruits)
Example 8.2.6 - Output
'cherry' ['apple', 'blueberry', 'banana']
Example 8.2.7 - remove(item)
- Removes the first occurrence of an item from the list.
fruits = ['apple', 'blueberry', 'banana', 'cherry']
fruits.remove('banana')
print(fruits) # Output: ['apple', 'blueberry', 'cherry']
Example 8.2.7 - Output
['apple', 'blueberry', 'cherry']
Example 8.2.8 - reverse()
- Reverses the order of the items in the list.
Example 8.2.8 - Output
['cherry', 'banana' , blueberry', 'apple']
Example 8.2.9 - sort()
- Sorts the items of the list in ascending order by default. To sort in descending order, use sort(reverse=True)
.
Example 8.2.9 - Output
[1, 1, 3, 4, 5, 9]
Python lists are versatile data structures that allow you to store and manipulate ordered collections of items. Using functions like append()
, clear()
, count()
, insert()
, len()
, pop()
, remove()
, reverse()
, and sort()
, you can efficiently manage and process data within your programs. These capabilities make lists an indispensable part of Python programming.
8.2d How to loop through a list
Looping through a list allows you to perform operations on each item in the list. Here are some common ways to loop through a list in Python:
1. Using a for
loop
Example 8.2.10 - The for
loop is the most straightforward way to iterate over each item in a list.
# List of favourite movies
favourite_movies = ['Inception', 'The Matrix', 'Interstellar', 'The Dark Knight', 'Pulp Fiction']
# Loop through each movie in the list
for movie in favourite_movies:
print(movie)
Inception The Matrix Interstellar The Dark Knight Pulp Fiction
2. Using enumerate()
Example 8.2.11 - If you need to access both the index and the value of each item in the list, you can use the enumerate()
function.
# List of favourite movies
favourite_movies = ['Inception', 'The Matrix', 'Interstellar', 'The Dark Knight', 'Pulp Fiction']
# Loop through each movie in the list with index
for index, movie in enumerate(favourite_movies):
print(f"{index}: {movie}")
Example 8.2.11 - Output
0: Inception 1: The Matrix 2: Interstellar 3: The Dark Knight 4: Pulp Fiction
3. Using a while
Loop
Example 8.2.12 - You can also use a while
loop to iterate over a list. This is less common but useful in some scenarios.
# List of favourite movies
favourite_movies = ['Inception', 'The Matrix', 'Interstellar', 'The Dark Knight', 'Pulp Fiction']
# Initialize index
index = 0
# Loop through the list using a while loop
while index < len(favourite_movies):
print(favourite_movies[index])
index += 1
Example 8.2.12 - Output
Inception The Matrix Interstellar The Dark Knight Pulp Fiction
There are more advanced ways to access lists like list comprehensions and map()
function which are out of the scope of this course.
8.2e Develop a program using lists as data structures
Exercise 8.2.1 - Given the following list of favourite books:
favourite_books = ['How it All Blew Up', 'The Kite Runner', 'The Time Machine', 'The Hunger Games', 'The Fault in Our Stars']
Perform the following tasks:
- Add the book 'Pride and Prejudice' to the end of the list.
- Insert the book 'To Kill a Mockingbird' at the second position in the list.
- Count how many times the book 'To Kill a Mockingbird' appears in the list.
- Remove the last book from the list.
- Reverse the order of the list.
- Sort the list in alphabetical order.
- Print the final list.
Write the complete program and show the output at each step.
Exercise 8.2.1 - Model Answer - Make sure to work out the exercise before checking the model answer.