Lists come up a lot in mathematical programming. There is still a little more we will need to know about them before we can use them effectively. In this section, we will look at using the length of a list, adding to a list, and creating lists.
The function len() gives the length of a list, which is how many elements the list contains. You may recall that we would look at how many items were in a list in order to determine how long to make a for loop run. Instead you can use len() to determine the stopping point of a loop. The code below shows you the basic concept of the function len().
Now consider what we were talking about: doing something with a list using a for loop and the lists length. Letβs take each element of a list, divide it by 3, round the result to two decimal places, and print it.
We could have used range(5) instead of range(len(theList)) since we know the list has 5 elements. However, using len() makes our code more flexible. If we later change the list to have more or fewer elements, we wonβt have to change the for loop. Think about this: we might not even be sure about the length of a list when we write the code. That may seem strange, but we could have very large lists or lists that change depending on some other aspect of the code. The len() function allows us to write code that will still "hit" every element of the list we want.
The append() function allows us to add elements to the end of a list. This is useful when we want to build a list as we go, rather than creating it all at once. Letβs look at a simple example to see how this works.
Notice that we needed a list to start with in order to use append(). We will not always know what is in the list ahead of time. This comes up when you are building a list based on some calculations or other code. In order to append the elements to the list, we will need to first create an empty list. This is written as "myList = []."
Something that will come up later is a list of lists. This is when each element of a list is itself a list. When we work with matrices, we will use a list of lists to represent the rows and columns.
You may want to use a variable here to hold the even number before cubing it and appending it to the list. This would be in the for loop. Something like: even = 2 * i.
First, create an empty list. Then, create a for loop that goes from 1 to 5. Inside the loop, calculate the even number, cube it, and append it to the list.
cubesOfEvens = []
for i in range(1,6):
even = 2 * i
cubesOfEvens.append(even ** 3)
print(cubesOfEvens) #prints [8,64,216,512,1000]