Loops and Lists
Last updated
Last updated
We don't typically just create lists with all of the values in them. Usually we get the lists dynamically (meaning we get them when the program is running either from a user, a file, the Internet or somewhere else). This means that we don't always know very much about our lists such as how big they are or what the values are inside the list. For this reason we might want to loop over all of the items in the list.
This looks almost like plain English and can hardly qualify as code right? The value num
in the loop declaration will be the value of the current item in the list. The loop will replace its value each iteration to be the current value.
Sometimes we want to know the index of the item in the list that we are looping over. You can do that with the enumerate function:
This time we have two variables: i
and num
. The i
variable will be the index and the num
variable will be the current item in the list.
One thing to keep in mind with dictionaries is that the pairs in the dictionary are not ordered. When you enter items into a list the items exist in the order that you added them but this is not the case with a dictionary. Dictionaries use a very efficient operation to store and retrieve data which makes it so they are not ordered like you would expect.
You can still iterate over dictionary though. This looks very similar to using a list.
To iterate over the keys and values at the same time you can use the items()
method.
So far, we have put numbers and strings into lists and we could imagine that they can also hold booleans right? But what if we wanted to have a list hold ... another list? Wouldn't that be cool! We call this a two-dimensional array (or list). We could print out a Tic-Tac-Toe game using a two dimensional list:
Try printing out a full Tic-Tac-Toe board (instead of the simple one I just did) using 2D arrays!