3. Lists#
3.1. Creating a list#
So far, we learned about simple data types like int
, float
, bool
, and str
. Python also offers a range of complex data types that allow us to store multiple related values (items) in a single variable and work with them at once. This is very useful in real world applications.
Each value in a list is called an item. List items are ordered, changeable, and allow duplicate values. A list is created by placing all the items (elements) inside square brackets [ ], separated by commas. It can have any number of items that can be of different types (integer, float, string etc.). A list can also have another list (a so-called sublist) as an item. A list with another list as an item is called a nested list. Below are some examples:
empty_list=[]
numbers=[0,1,2,3,4,5,6]
strings=["hello", "there", "this", "is", "Python", "handbook"]
mixed=[1, 2.5,"python", True]
nested_list = [3, [1.5, 2], [True, False], ""]
# Let's print the nested_list:
print(nested_list)
[3, [1.5, 2], [True, False], '']
3.2. List indexing#
To access the items in a list we use their index. Items are indexed in two ways:
positive indexing: the first item has index [0] , the second item has index [1], etc.
negative indexing: We can also use negative indexing in Python. It counts the items backwards from the end of the list, starting at -1. Below you can see an example of a list with positive and negative indices:
strings=["hello","there","this","is","Python","handbook"]
List: strings |
‘hello’ |
‘there’ |
‘this’ |
‘is’ |
‘python’ |
‘handbook’ |
---|---|---|---|---|---|---|
positive index |
0 |
1 |
2 |
3 |
4 |
5 |
negative index |
-6 |
-5 |
-4 |
-3 |
-2 |
-1 |
Note that accessing an index which does not exist generates an error. For a nested list, we first provide the index of the main list and then the index for the list that is stored within the main list.
numbers=[0,1,2,3,4,5,6]
print(numbers[0]) # positive indexing
0
strings=["hello","there","this","is","Python","handbook"]
print(strings[1]) # positive indexing
there
nested_list = [3, [1.5, 2], [True, False], ""]
print(nested_list[2]) # positive indexing
[True, False]
nested_list = [3, [1.5, 2], [True, False], ""]
print(nested_list[2][1]) # nested list indexing
False
strings=["hello","there","this","is","Python","handbook"]
print(strings[-2]) # negative indexing
Python
numbers=[1,2,3,4]
print(numbers[4]) # accessing non-existent index
# numbers[4] would be the fifth item in this list, but this list has four items.
# Hence, an error is generated
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Cell In[8], line 2
1 numbers=[1,2,3,4]
----> 2 print(numbers[4]) # accessing non-existent index
3 # numbers[4] would be the fifth item in this list, but this list has four items.
4 # Hence, an error is generated
IndexError: list index out of range
3.2.1. Exercise: Indexing#
In this exercise, you must access certain items within the lists that are provided. For each subquestion, you have to choose whether you want to use positive or negative indexing.
Below is the list: fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi']
. Use both positive or negative indexing to access the following items within this list:
The first item in the list.
The second item in the list.
The last item in the list.
The third item from the end of the list.
fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi']
# A) The first item
first_item = # your code here
print("First item:", first_item)
# B) The secon item
second_item = # your code here
print("Second item:", second_item)
# C) The last item
last_item = # your code here
print("Last item:", last_item)
# D) The third item from the end
third_from_end = # your code here
print("Third item from the end:", third_from_end)
Given is the list: pets
, consisting of three sublists which group categories of pets together. Use both positive or negative indexing to access the following items:
The third sublist.
The fourth item within the second sublist.
The item called
Cat
. (Optional)
💡 Hint: An element of a nested list like this one can be accessed using the same kind of indexing as with one-dimensional lists. However this time, you may need to index two values; i.e. the sublist and the item within that sublist. For instance, if you want to obtain the third sublist’s second item, you write: pets[2][1]
. (The 2 corresponds to the third sublist, and the 1 corresponds to the second item in this sublist.)
pets = [['Dog', 'Cat'],
['Canary', 'Parrot', 'Cockatiel', 'Pigeon'],
['Goldfish', 'Axolotl', 'Turtle']]
# E) The third sublist
third_sublist = # your code here
print("Aquatic Pets:", third_sublist)
# F) The fourth item within the second sublist.
fourth_item_second_sublist = # your code here
print("A Common Bird Type:", fourth_item_second_sublist)
# G) The item called Cat (Optional)
item_cat = # your code here
print("Your New Feline Friend:", item_cat)
3.2.2. Exercise: Indexing of a 3x3 nested list#
This exercise is split into three parts, designed to challenge you on the topic of nested lists.
Task 1: Create a 3x3 matrix as a nested list, where each element is a single-digit number you may choose yourself.
Task 2a: Let the program print the first element of the first column.
# Task 1: Creating a 3x3 matrix
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# Task 2a: Print the first element of the first column
# your code here
Task 2b: Write a Python program that calculates and displays the sum of the elements along the main diagonal of the matrix (from the top-left to the bottom-right, i.e., 1+5+9).
# Task 2b: Calculate the sum of main diagonal elements
sum_main_diagonal = # your code here
# Display the sum of main diagonal elements
print(f"Sum of main diagonal elements: {sum_main_diagonal}")
Task 3: Write a Python program that calculates and displays the sum of the elements in the last column of the matrix.
# Task 3: Calculate the sum of elements in the last column
sum_last_column = # your code here
# Display the sum of elements in the last column
print(f"Sum of elements in the last column: {sum_last_column}")
3.3. List slicing#
We can call up a few items from a list in a sublist. This is called slicing. The correct syntax for doing this is [start:end:step]
. This means you will get the items starting at start
index at every step
\(^{th}\) item until right before the end
index.
Note that the end
\(^{th}\) item will not be included.
numbers=[0,1,2,3,4,5,6]
print(numbers[2:5:1]) # output: [2, 3, 4]
print(numbers[2:5:2]) # output: [2, 4]
print(numbers[-1:-5:-2]) # negative indexing, [6, 4]
We can also skip some of the elements in the slicing syntax. Here is how they will be interpreted:
Syntax |
Description |
---|---|
[start : end : step] |
from |
[start : end] |
step=1 |
[start : : step] |
end = last index |
[ : end : step] |
start=0, first index |
[ : ] |
all elements in the list with step=1 |
numbers=[0,1,2,3,4,5,6]
print(numbers[2:5])
print(numbers[:3]) # start=0, end=3, step =1
print(numbers[1::2]) # start=1, end= last, step =2
print(numbers[-5:]) # negative indexing, start=-5, end= last, step =1
print(numbers[::-1]) # negative steps, start=last, end=0, step =-1
3.3.1. Exercise: Sublist extraction#
Given below is the main list count_to_ten
. In this exercise, you must use list slicing to create and print the new lists called count_down
, even_numbers
and sublist
as described below. Note that you may only do this by extracting sublists from the main list.
Create and print a new list named
count_down
containing elements from 10 to 1.Create and print a new list named
even_numbers
containing only the even integers fromcount_to_ten
.Create and print a new list named
sublist
by extracting the sublist [5, 10] from thecount_to_ten
list.
# Initialise your main list first:
count_to_ten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# A) Elements from 10 to 1
count_down = # your code here
print(f"Count Down List: {count_down}")
# B) Even integers from count_to_ten
even_numbers = # your code here
print(f"Even Integer List: {even_numbers}")
# C) Sublist [5, 10] from count_to_ten
specific_indexes = # your code here
print(f"Specific Indexes Sublist: {specific_indexes}")
3.4. Modifying items (reassigning values) in a list#
You can modify an item in a list simply by using list[index] =
. However, you need to access that item using correct list indexing. Here is an example where two items in a list are modified:
numbers=[0,1,2,3,4,5,6]
# to modify the first item with value "Zero"
numbers[0] = "Zero"
# to modify the third item with value "Two"
numbers[2] = "Two"
print(numbers)
To modify multiple items simultaneously, you can use list slicing:
# to modify multiple items
numbers[4:7]=["Four","Five","Six"]
print(numbers)
Attention: Be very careful with indexing! Below is what happens if you use a wrong indexing compared to what you have in mind. It doesn’t give an error but provides different results than intended.
# example 1: adding one extra item for not using the correct end step
numbers=[0,1,2,3,4,5,6]
numbers[3:5]=["Three","Four","Five"]
print(numbers)
# example 2: creating nested lists
numbers=[0,1,2,3,4,5,6]
numbers[3]=["Three","Four","Five"]
print(numbers)
3.5. Removing an item from a list#
To remove an item you can use the del
statement. Here is a quick example:
numbers=[0,1,2,3,4,5,6]
del numbers[4:]
print(numbers)
3.5.1. Exercise: Del statement (Optional)#
Given is the list potential_snacks
, containing the snacks you plan on buying for a movie night you are hosting. However, you come to realise one of your guests has a peanut allergy and another one is allergic to chocolate. Hence, you want to update your list by doing the following:
Remove Peanuts
and Chocolate Bars
from your list of potential snacks using the del
statement.
potential_snacks = ['Chips', 'Peanuts', 'Chocolate Bars', 'Cookies', 'Mochi']
# Your code here
print(f"The Snacks You Can Still Buy Are: \n {potential_snacks}")
3.6. Python list methods#
Here is a list of built-in operations and methods you can perform on lists. It’s good enough for now to know that these operations exist and that you can use them. If you need them later, you can search online for the correct syntax and examples.
Syntax |
Description |
---|---|
+ |
concatenate (join) two lists |
* |
multiply a list |
append() |
add a new element at the end of the list |
extend() |
add multiple elements at the end of the list |
insert() |
insert elements at given indexes |
remove() |
remove an element from the list (only the first occurrence) |
pop() |
remove an element using its index |
Reverse() |
reverse the elements |
len() |
length of the list |
count() |
count the number of occurences of an element |
sort() |
sort the elements |
clear() |
clear the list |
3.6.1. Exercise: Shopping list#
Start by creating a list called shopping_list
with the items: “Apples”, “Milk”, “Bread”, “Eggs”, and then perform the following operations on it:
Using
append
to add “Butter” to the list.Remove “Bread” from the list.
Create a new list called
special_offers
with the items: “Chips (50% off)”, “Soda (25% off)”.Using
append
add thespecial_offers
list to the shopping list.Print the length of the list to see how many items it has.
# Initialising the list:
shopping_list = # your code here
# A) Add "Butter" to the list.
shopping_list.append(# your code here)
print(f"A) Shopping List With Butter Added: {shopping_list}")
# B) Remove "Bread" from the list.
# your code here
print(f"B) Shopping List With Bread Removed: {shopping_list}")
# Initialising the list again after A) and B) have been performed
shopping_list = ["Apples", "Milk", "Eggs", "Butter"]
# C) Create a new list called "special_offers"
# This list contains the following items: "Chips (50% off)", "Soda (25% off)".
special_offers = # your code here
print(f"C) Special Offers: {special_offers}")
# D) Add "special_offers" to the shopping list.
# your code here
print(f"D) Shopping List and Special Offers: {shopping_list}")
# E) Print the length of the shopping list
# your code here
3.6.2. Summarising Exercise: Extensive list manipulation#
This exercise will use a bit of everything you have learned so far to make a list of your liking. You can create a list with items you may choose yourself and then you must perform the following operations on it:
Start by creating
my_list
(containing four items).Print the first item in your list.
Delete the fourth item in your list.
Append two new (separate) items to your main list. Again, you may name these two items as you please.
Change the second and third item in your list to something else. (An example would be changing the second item to ‘Hermit Purple’ and the third item to ‘Hierophant Green’.)
Lastly, reverse all items in your list.
# A) Create your list of four items
my_list = # your code here
print(f"A: {my_list} \n")
# B) Print the first item
first_item = # your code here
print(f"B: {first_item }")
# C) Delete the fourth item
del # your code here
print(f"C: {my_list}")
# D) Append two new (separate) items
my_list.append(# your code here)
my_list.append(# your code here)
print(f"D: {my_list}")
# E) Change 2nd and 3rd item
# your code here
print(f"E: {my_list}")
# F) Reverse your list
# your code here
print(f"F: {my_list}")