Chapter 6 - Lists

This notebook uses code snippets and explanations from this course

As we have learned before, strings and integers have one value in them. When we put a new value in them, the old value is overwritten. In this chapter we will have a first look at containers. A container allows us to put many values in a single box. A container is nice because we can carry lots of values around in one convenient package. It is very straightforward to store a list of items as a container. Not surprisingly, we call this a list.

At the end of this chapter, you will be able to:

  • create a list
  • add items to a list
  • extract/inspect items in a list
  • perform basic list operations
  • use built-in functions on lists

If you want to learn more about these topics, you might find the following links useful:

If you have questions about this chapter, please refer to the forum on Canvas.

1. How to create a list

It's very simple to create a list. Please look at the following examples:


In [ ]:
friends = ['John', 'Bob', 'Mary']
stuff_to_pack = ['socks','shirt','toothbrush']
print(friends)
print(stuff_to_pack)
  • Lists are surrounded by square brackets and the elements in the list are separated by commas
  • A list element can be any Python object - even another list
  • A list can be empty

In [ ]:
#list of integers
print([1, 24, 76])

#list of strings
print(['red', 'yellow', 'blue'])

#mixed list
print(['red', 24, 98.6])

#list with a list included
print([ 1, [5, 6], 7])

#empty list
print([])

Please note that there are two ways of creating an empty list


In [ ]:
one_way = []
print(one_way)

In [ ]:
another_way = list()
print(another_way)

2. How to add items to a list

the most common way of adding an item to a list is by using the append method. Let's first look at the help message of this method to understand it better:


In [ ]:
help(list.append)

We learn that append has one positional argument object and it returns None. It might be a bit confusing at first that a list method returns None. Please carefully look at the difference between the two following examples. Please predict what will be printed in each code snippet below:


In [ ]:
a_list = [1, 3, 4]
a_list.append(5)
print(a_list)

In [ ]:
a_list = [1, 3, 4]
a_list = a_list.append(5)
print(a_list)

The reason why the first example is the correct one is because lists are mutable, which means that you can change the contents of a list. You can hence change the items in a list without assigning it to a new variable. This also becomes clear when you look at the documentation:


In [ ]:
help(list.append)

In comparison, when we want to change a mutable object like a string, the method returns a copy of the input:


In [ ]:
help(str.replace)

In [ ]:
a_string = 'hello'
a_string.replace('l', 'b')
print(a_string)

In [ ]:
a_string = 'hello'
a_new_string = a_string.replace('l', 'b')
print(a_new_string)

3. How to extract/inspect items in a list

Please note that indexing and slicing works the same way as with strings. Every item in the list has hence its own index number. We start counting at 0! The indices for our list ['John', 'Bob', 'Marry'] are as follows:

John Bob Mary
0 1 2
-3 -2 -1

We can hence use this index number to extract items from a list (just as with strings)


In [ ]:
friend_list = ['John', 'Bob', 'Marry']
print(friend_list[0])
print(friend_list[1])
print(friend_list[2])

Obviously, we can also use negative indices:


In [ ]:
friend_list = ['John', 'Bob', 'Marry']
print(friend_list[-2])

And we can extract one part of a list using slicing:


In [ ]:
friend_list = ['John', 'Bob', 'Marry']
list_with_fewer_friends = friend_list[:2]
print(list_with_fewer_friends)

If you insert an index that is higher than what is present in the list, you will get an IndexError:


In [ ]:
print(friend_list[5])

Two additional methods are useful for inspecting lists:

  • count
  • index

In [ ]:
help(list.count)

the count method has one positional argument value and returns an integer. As the name already indicates, the method returns how often the value occurs in the list.


In [ ]:
friend_list = ['John', 'Bob', 'John', 'Marry', 'Bob']
number_of_bobs = friend_list.count('Bob')
print(number_of_bobs)

In [ ]:
friend_list = ['John', 'Bob', 'John', 'Marry', 'Bob']
number_of_franks = friend_list.count('Frank')
print(number_of_franks)

In [ ]:
help(list.index)

The index method has one positional argument value and returns the first index of the value. It is hence similar to the count method, but now the first index is returned of the value instead of the count.


In [ ]:
friend_list = ['John', 'Bob', 'John', 'Marry', 'Bob']
first_index_with_john = friend_list.index('Bob')
print(first_index_with_john)

We get a ValueError when the value is not in the list


In [ ]:
friend_list = ['John', 'Bob', 'John', 'Marry', 'Bob']
friend_list.index('Frank')

4. Basic List Operations

Python allows at least the following very useful list operations:

  • concatenation
  • repetition
  • membership
  • comparison

The '+' sign concatenates two lists:


In [ ]:
one_list = ['where', 'is']
another_list = ['the', 'rest', '?']
print(one_list + another_list)

The '*' sign makes it possible to repeat a list:


In [ ]:
a_list = ['Hello', 'world']
print(a_list * 3)

Of course, you can use lists in membership boolean expressions


In [ ]:
life = ['a', 'lot', 'of', 'stuff']
print('meaning' in life)

And you can use lists in comparison boolean expressions


In [ ]:
print([3, 2] == [2, 3])

5. Use built-in functions on lists

Python has a range of functions that operate on lists. We can easily get some simple calculations done with these functions:


In [ ]:
nums = [3, 41, 12, 9, 74, 15]
print(len(nums)) # number of items in a list
print(max(nums)) # highest value in a list
print(min(nums)) # lowest value in a list
print(sum(nums)) # sum of all values in a list

6. An overview of list methods

There are many more methods which we can perform on lists. Here is an overview of some of them. In order to get used to them, please call the help function on each of them (e.g. help(list.insert)). This will give you the information about the positional argument, keyword arguments, and what is returned by the method.


In [ ]:
#define some lists and variables
a = [1,2,3]
b = 4
c = [5,6,7]
x = 1
i = 2

#do some operations 
a.append(b)     # Add item b to the end of a
a.extend(c)     # Add the elements of list c at the end of a
a.insert(i,b)   # Insert item b at position i
a.pop(i)        # Remove from a the i'th element and return it. If i is not specified, remove the last element
a.index(x)      # Return the index of the first element of a with value x. Error if it does not exist
a.count(x)      # Return how often value x is found in a
a.remove(x)     # Remove from a the first element with value x. Error if it does not exist
a.sort()        # Sort the elements of list a
a.reverse()     # Reverses list a (no return value!)

print(a)

In order to have a complete overview of all list methods, you can use the dir built-in function:


In [ ]:
dir(list)

Exercises

Exercise 1:

Create an empty list and add three names (strings) to it using the append method


In [ ]:
# your code here

Exercise 2:

Please count how many times John occurs in the list


In [ ]:
friend_list = ['John', 'Bob', 'John', 'Marry', 'Bob']

#  your code here

Exercise 3:

Please use a built-in function to determine the number of strings in the list below


In [ ]:
friend_list = ['John', 'Bob', 'John', 'Marry', 'Bob']

# your code here

Exercise 4:

Please remove both John names from the list below using a list method


In [ ]:
friend_list = ['John', 'Bob', 'John', 'Marry', 'Bob']

# your code here

Exercise 4:

Please add world to the string and the list below. Only create a new object if it is necessary.


In [ ]:
a_string = 'hello'
a_list = ['hello']

# your code here