earnings = [91, 87, 115, 108]
The values are separated by commas, and enclosed in square brackets. We can access the individual elements as follows:
earnings[0]
earnings[1]
earnings[3]
The numbers 0, 1, and 3 are called indices (the singular is index). Note that we start from 0. The list earnings is of length 4 (since it has four elements), so the last possible index will be 3.
We can get the length of a list using the len() function:
len(earnings)
We have all the tools in order to print every element of a list in turn. For example, suppose we need to print, in turn, earnings[0], earnings[1], ... earnings[3]. In other words, suppose we need to print earnings[i] for every i between 0 and 3 inclusive. The way to do this is to use a for-loop:
for i in range(4):
print("You make", earnings[i], "thousand dollars a year!")
We can make this a little nicer. We used for i in range(4) because we know that we need the index i to range from 0 to 3 because we know that earnings contains 4 elements. But we can use len(earnings) instead of 4 to get the same results:
for i in range(len(earnings)):
print(earnings[i])
If all we want to do is to print (or use somehow) the elements of the list earnings, there is a nicer way to do this using for. Note that the following is a new way of using for:
for amt in earnings:
print(amt)
for <elem> in <list> puts the elements of <list> into the variable <elem>, in turn.
Suppose we want to convert the amounts from US dollars to Canadian dollars. Here is how you might try to do this:
USD_TO_CAD = 1.3
for amt in earnings:
amt *= USD_TO_CAD
print('amt is now', amt)
print('earnings is now', earnings)
The value of amt changed every time, but earnings never did! What happenned? You can think of for amt in earnings variant as:
for i in range(len(earnings)):
amt = earnings[i]
amt *= USD_TO_CAD
It's clear why this wouldn't change earnings: what's changed is the variable amt, but not earnings[i]. It's the same situation as
a = 42
b = a
b = 43
b changes, but a would still be 42.
How can we change earnings? Just loop over all the indices.
USD_TO_CAD = 1.3
for i in range(len(earnings)):
earnings[i] *= USD_TO_CAD
print(earnings)
A list L is non-decreasing if for every i, $L[i] \geq L[i-1]$. For example, [1, 2, 3, 3, 5, 100, 200] is non-decreasing, but [1, 0, 5, 6] is not, since its second element is smaller than its first element.
Let's write the function is_non_decreasing(L) that returns True iff L is non-decreasing.
def is_non_decreasing(L):
'''Return True iff L is non-decreasing
Arguments:
L -- a list of integers
'''
for i in range(1, len(L)): #start at i = 1, since it makes no sense to compare L[0] and L[-1]
if L[i] < L[i-1]:
return False #L is definitely not non-decreasing
#Checked for every i, and didn't return False, so we can return True
return True