4. Lists#

Exercise 4.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"]

print(f'This book series consists of {len(titles)} titles.')

last_two = titles[-2:]
print(last_two)

## An alternative solution with the exact same effect
last_two = titles[5:]
print(last_two)

Exercise 4.2.#

Create the following list:

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

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

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

colours.append('orange')
colours.append('yellow')

# Let's see the results
print(colours)

Exercise 4.3.#

Create the following list:

cities = ['Madrid','Helsinki','Paris','Brussels','London','Rome','Warsaw','Amsterdam']

Mext, create a new list named sorted_cities in which the elements are sorted alphabetically.

cities = ['Madrid','Helsinki','Paris','Brussels','London','Rome','Warsaw','Amsterdam']

sorted_cities = sorted(cities)
print(sorted_cities)
['Amsterdam', 'Brussels', 'Helsinki', 'London', 'Madrid', 'Paris', 'Rome', 'Warsaw']

Exercise 4.4.#

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 and 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.
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

# Use my_list.append(item_to_add) to add items to a list
plays.append('Macbeth')
plays.append('Othello')

Next, count the number of plays in this list.

# Use the len(my_list) function to count the items in the list
print( f'This list contains {len(plays)} plays.' )

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

print( f"The first play in the list is '{plays[0]}'." )
print( f"The last play in the list is '{plays[-1]}'." )

Exercise 4.5.#

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.

# First we split the string into a list of words
words = quote.split()

# Now we can count the number of words, which is the number of elements in our list
print( f'The quote contains {len(words)} words.' )
The quote contains 59 words.

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

# The last word is the word with index -1 in our list
print( f'The last word is \'{words[-1]}\'.' )
# Note how it includes the '.'?
# In many cases, you will want to make sure that you remove such punctuation before processing text.
print( f'The last word is \'{words[-1].strip(".")}\'.' )

# How many times does "place" occur in the quote?
print(f"There are {words.count('place')} occurrences of the word 'place'.")

# If you want to count "PlAcE" and "place" as occurrences of the same word, you can convert the quote to lower case before your start the analysis.
count = 0

words = quote.lower().split()
count = words.count('place')

print( f"There are {count} occurrences of the word 'place', counted in case-insensitive way.")
The last word is 'sunshine.'.
The last word is 'sunshine'.
There are 4 occurrences of the word 'place'.
There are 4 occurrences of the word 'place', counted in case-insensitive way.