5. Lists#

The variables that were discussed in the previous tutorials were all assigned single values, such as strings, integers or floating point numbers. It is also possible to work with variables that contain collections of values.

One example of a variable type that can hold multiple values is the list. Lists can be created by surrounding all the values that you want to gather by square brackets. The individual values within such lists need to be separated by commas.

The statement below creates a list containing the five days of the working week:

week = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" ]  

The things that are in the list are referred to as elements or items. The elements in week are all strings. The elements do not all have to be of the same type, however. It is allowed to mix strings with integers, for instance.

Accessing individual items#

When lists are created in this manner, the items in this list are given a certain order. Python numbers the elements in the list automatically, following the order in which these values were given. These numbers will function as indices that can be used to access the individual items in the list. Bear in mind that Python starts counting at 0.

In the example above, the element "Monday" is assigned the index 0, and the element "Thursday" will have the index 3. As is the case for strings and their individual characters, the separate elements in the list can be accessed using the square bracket notation.

print( week[3] )
# This prints "Thursday"

print( week[-1] )
# This prints "Friday"

Another similarity between lists and strings is that the lengths of both types of variables can be found using the len() function. In the case of lists, len() returns the number of elements in the list.

print( len(week) )
# This prints 5

List slicing#

Like strings, lists can also be sliced. Slicing means selecting a part of a list (or string). To do this, you need to type in a set of square brackets directly following the name of the list. Within these brackets, you need to give a pair of indices, specifying the first and the last item you want to retrieve. These two numbers need to be separated by a colon. The item whose index is to the right of the colon is not included in the selection. If you state that the selection should stop at index 3, for instance, the last item in the selection will be the item with index 2.

If you leave out the first number, Python will start at the beginning of the list. If you omit the second number, the selection will continue until the very last item in the list.

week_part = week[1:3]
## Selects Tuesday' and 'Wednesday'
print(week_part)
week_part = week[:2]
## Selects 'Monday' and 'Tuesday'
print(week_part)
week_part = week[3:]
## Selects 'Thursday'and 'Friday'
print(week_part)

Exercise 5.1#

The list named titles below brings together a number of book titles. Print a sentence that gives information about the number of books in this list of titles. Next, create a new list named last_two containing only the last two titles in this series.

titles = ["Philosopher's Stone","Chamber of Secrets",
          "Prisoner of Azkaban","Goblet of Fire",
          "Order of the Phoenix","Half-Blood Prince",
          "Deathly Hallows"]

Adding items to a list#

The append() method can be used to add items to an existing list. This is a method, which is part of the list and therefore needs to be called in the my_list.append(new_item) syntax. Functions and methods will be discussed later in the tutorial.

week.append("Saturday")
week.append("Sunday")

print( f"The list now contains {len(week)} items." )

Exercise 5.2.#

Create the following list:

colours = ['green','blue','red']

Add the colours ‘orange’, ‘yellow’ to this list.

Sorting#

The items in a list can be arranged alphabetically or numerically using the sorted() function.

unsorted_list = [ 5, 8, 2, 9, 1, 8 ]
print( sorted( unsorted_list ) )

## The output is as follows:
## [1, 2, 5, 8, 8, 9]

Presence in a list#

If you want to know whether a list contains a given item, you use the in operator. This operator takes two operands, i.e. things to operate on. To the left of in, you mention the item you want to search for. On the right you mention the list in which you want to search. Using in, you can create a Boolean expression, an expression which can be either true or false.

# Is 2 in [1, 2, 3]? Yes, so this returns True
2 in [1, 2, 3]
if 'Monday' in week:
    print('This item is indeed in the list!')

Exercise 5.4.#

We have two lists of numbers and would like to know which numbers in the first list are not in the second list. Write code which can extract those numbers from the first list that are not in the second list.

first = [4, 9, 1, 17, 11, 26, 28, 54, 63] 
second = [8, 9, 74, 21, 45, 11, 63, 28, 26]

numbers_not_in_second = []

# Add the numbers from `first` that are not in `second` to `numbers_not_in_second`

print(numbers_not_in_second)

Counting items#

You can count the number of times an item occurs in a list by making use of the count() method.

This method needs to be appended after the name of the list, using a dot. As a parameter to this method, you provide the item that you want to count.

my_list.count(item_to_count)

As an example, we ask how many times the string "cat" appears in the list of animals.

animals = [ 'cat' , 'dog' , 'rabbit' , 'elephant' , 'cat' , 'cat' , 'giraffe']

print( f"The word 'cat' occurs {animals.count('cat')} times in this list." )

Exercise 5.5.#

The list below contains the titles of first twelve plays written by William Shakespeare.

plays = [
    'Comedy of Errors',
    'Henry VI, Part I',
    'Henry VI, Part II',
    'Henry VI, Part III',
    'Richard III',
    'Taming of the Shrew',
    'Titus Andronicus',
    'Romeo and Juliet',
    'Two Gentlemen of Verona',
    'Love\'s Labour\'s Lost',
    'Richard II',
    'Midsummer Night\'s Dream'
]

Add the following two titles to this list:

  • Macbeth

  • Othello

Next, count the number of plays in this list.

Print the titles of the first and the last plays in the list, using the index of these items.

Print the full list in alphabetical order using the for keyword.

for 

Exercise 5.6.#

We have a list of websites and are interested to find the Dutch ones.

Write some code to select the Dutch websites from this list. Tip: You may want to reuse some of the code developed for exercise 3.4.

websites = [
    'https://www.universiteitleiden.nl',
    'https://www.stanford.edu',
    'https://www.uu.nl',
    'http://www.ox.ac.uk',
    'https://www.rug.nl',
    'https://www.hu-berlin.de',
    'https://www.uva.nl'
]

# Print the URLs that belong to Dutch institutions

Exercise 5.7.#

We have a quote from E.M. Forster’s A Room with a View below and want to get a few statistics about it.

quote = '''We cast a shadow on something wherever we stand, and it is no good 
moving from place to place to save things; because the shadow always follows. Choose 
a place where you won’t do harm - yes, choose a place where you won’t do very much 
harm, and stand in it for all you are worth, facing the sunshine.'''

First we’d like to know the total number of words. Here we say that the words are all the strings separated by spaces. That means “won’t” is a word in the quote, as well as “stand,” (including the comma). It depends on the context of the research if this is okay, or that you need to further process the words before you count them.

We can convert a string to a list of words, using the split() method. This method can convert a string into a list, based on a character or space that occurs in this string. This split() method must be added after the the string variable, using a dot, as follows:

quote.split(string_to_split_on)
quote.split()
# Not specifying what to split on is the same as splitting by a space, like this:
quote.split(' ')

Use this split() method to give information about the total number of words in this quote.

Print the last word in the quote, and count the number of occurrences of the word “place”.

# Print the last word


# Count the number of occurrences of "place" in the quote