Lists and Loops#

This notebook is based on materials kindly provided by the IN1900 team.

Lists#

Python lists can contain int, float, String and other items. We make a list by placing the items in square brackets, [], separated by commas.

my_list = [1, 2]

There are many functions for working with lists. One example is len(), which returns the length of the list, in other words the number of items it contains.

odd = [1, 3, 5, 7, 9]

print("odd: ", odd)
print("length of list 'odd' :", len(odd))
odd:  [1, 3, 5, 7, 9]
length of list 'odd' : 5

Adding (Appending) Elements to a List#

We can add/append elements to an existing list. Below we first make an empty list, and then append one element at a time using append(). Note that append() adds items at the end of the list.

empty_list = []

empty_list.append("not")
empty_list.append("so")
empty_list.append("empty")
empty_list.append("anymore")

print(empty_list)
['not', 'so', 'empty', 'anymore']

Exercise: Adding Elements to a List #

The list days below contains the weekdays, but is missing the weekend. Your task will be to add Saturday and Sunday to the existing list days.

Start by printing out the length of the list days using the function len(). Then, add the two days of the weekend to days. Finish by printing out the new length of the list using the len()-function.

An example of how your output could be:

There are 5 days!
There are 7 days!

The text is not strictly necessary, the numbers are the important part!

days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]  # DO NOT CHANGE THIS LINE

# PRINT THE LENGTH OF THE LIST 

# ADD THE DAYS OF THE WEEKEND HERE

# PRINT THE LENGTH OF THE LIST AGAIN

Hint : remember that Saturday and Sunday need to be of type str, else you will get a NameError.

Accessing List Elements - List Indexing#

To get an item from a list, we use an index number.

Python counts from 0, not 1!

We can get the items in odd one at a time:

print('odd[0] = ', odd[0])
print('odd[1] = ', odd[1])
print('odd[2] = ', odd[2])
print('odd[3] = ', odd[3])
print('odd[4] = ', odd[4])
odd[0] =  1
odd[1] =  3
odd[2] =  5
odd[3] =  7
odd[4] =  9

Exercise: Indexing Lists#

Change the variable index in the code below such that the word something is printed when the code snippet is run.

Margaret_Lanterman = ['my', 'log', 'has', 'something', 'to', 'tell', 'you.']

index = -1
print(Margaret_Lanterman[index])
you.

Nested Lists#

Lists are frequently used in Python. Later we will see an example of lists of cases from US case law. Lists can contain other lists. In the list of cases, each case has a list of attorneys.

We can make a new list even to complement our list odd.

even = [2, 4, 6, 8, 10]

Making a List of Lists#

Now, we can make a new list containing the lists odd and even.

odd_and_even = [odd, even]
print("odd_and_even : ", odd_and_even)
print("Second object in odd_and_even is the list even : ", odd_and_even[1])
print("First number in even: ", odd_and_even[1][0])
print("Third number in even: ", odd_and_even[1][2])
odd_and_even :  [[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]
Second object in odd_and_even is the list even :  [2, 4, 6, 8, 10]
First number in even:  2
Third number in even:  6

Exercise: Dates and Indexing Nested Lists#

Change the indexes in the code below, so that the printed information is correct.

summer = ["June", "July", "August"]
autum = ["September", "October", "November"]
winter = ["December", "January", "February"]
spring = ["March", "April", "May"]

months = [summer, autum, winter, spring]


# change the indices below
print("My birthday is the Xth of {}.".format(months[0][2]))
print("Christmas is the Xth of {}.".format(months[1][1]))
My birthday is the Xth of August.
Christmas is the Xth of October.

Loops#

We saw above how we could manually get each element in a list. However, this kind of repetition is tedious and error-prone. For example, if we change odd to be a shorter list, we will get an error when re-running the code we wrote above:

odd = [1, 3, 5, 7]

print('odd[0] = ', odd[0])
print('odd[1] = ', odd[1])
print('odd[2] = ', odd[2])
print('odd[3] = ', odd[3])
print('odd[4] = ', odd[4])
odd[0] =  1
odd[1] =  3
odd[2] =  5
odd[3] =  7
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In[10], line 7
      5 print('odd[2] = ', odd[2])
      6 print('odd[3] = ', odd[3])
----> 7 print('odd[4] = ', odd[4])

IndexError: list index out of range

This code violates an important principle in programming: Don’t Repeat Yourself (DRY). To avoid such errors, we should leave the work of keeping track of the list elements to the computer.

for number in odd:
    print(number)

We can read the code above as: for each number in odd, do the following: print the number.

Exercise: Loop#

We can also loop or iterate over lists of strings. Complete the following code, to loop (iterate) over the summer months. The expected output is:

June
July
August
months = ["June", "July", "August"]

for month in months:
    "your code here"

Visualizing loops#

It might be helpful to illustrate loops with an animation. Here, we iterate over a list of strings:

sentence = ['a', 'short', 'list']

print("Iterating over the sentence:")
for word in sentence:
    print(word)

For each iteration of the loop, the variable word changes to the next element in the list:

Nested Loops#

When we put a loop inside another loop, we call them nested loops. We can use nested loops to iterate over nested lists.

Remember that odd_and_even = [odd, even].

for items in odd_and_even:
    for number in items:
        print(number)

Exercise: Nested Loops#

Next, we iterate over a nested list of strings: Complete the following code, to loop (iterate) over all the months.

You will need two nested for-loops.

summer = ["June", "July", "August"]
autum = ["September", "October", "November"]
winter = ["December", "January", "February"]
spring = ["March", "April", "May"]

seasons = [summer, autum, winter, spring]

for # your code here

Bonus Material: Iterating over Numbers with range()#

for-loops iterate over all the elements in a sequence, frequently a list. We can also loop over other kinds of sequences. The function range() returns a sequence of numbers:

print("Using range:")
for i in range(4):
    print(i)

Exercise: Indexing in a Loop#

The list names contains a few names and the list birth_years contain their corresponding birth years. There is also a for-loop that should print out the names with their corresponding birth years. The print-statement is incomplete, such that only the name is printed.

Your task is to add the correct birth year in the print-statement in the loop by indexing birth_years.

names = ["John Cleese", "Terry Gilliam", "Eric Idle", "Michael Palin", "Graham Chapman", "Terry Jones"]
birth_years = [1939, 1940, 1943, 1943, 1941, 1942]

for i in range(len(names)):
    print(names[i], "was born in")

range(start, stop, step_length)#

range() can have up to three arguments. If you give all three arguments, range will yield integers starting from and including start, up to but excluding stop, in steps of size step_length.

If you only give two arguments, the step length will be 1.

If you only give a single argument, the starting point will be zero.

Exercise: Using range #

Predict what will be printed when running the code snippet below:

for i in range(0, 3, 2):
    print(i)

Exercise: Using range when Indexing #

Predict what will be printed when running the code snippet below:

message = ["You", "don't", "understand!"]

for i in range(0, 3, 2):
    print(message[i])

Exercise: Nested Loops and range()#

We can also use nested loops with range. Explain the loop below.

for i in range(4):
    print("Main loop i =", i)
    for j in range(i+1):
        print("\tInner loop j =", j, "  (i =", i, ")")

Key Points#

  • We can make lists of items

  • We use indexes to access items in lists: things[3] or many_things[0][4]

  • Modify lists using append() and other functions

  • Use for-loops to iterate over lists