Data Structures

Working with Lists

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.

my_list = [1, 2, 3, 4, 5]
for num in my_list:
  print num

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:

for i, num in enumerate(my_list):
  print i, num

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.

Dictionaries

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.

for key in my_dict:
  print "the value is: %s" % my_dict[key]

To iterate over the keys and values at the same time you can use the iteritems() method.

for key, value in my_dict.iteritems():
  print "key: %s, value: %d" % (key, value)

Lists of lists or 2D arrays/lists

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:

def print_2d(l):
  for i in l:
    for j in i:
      print j,
    print

my_list = [ ['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-'] ]

print_2d(my_list)

my_list[1][1] = 'x'

print_2d(my_list)

Try printing out a full Tic-Tac-Toe board (instead of the simple one I just did) using 2D arrays!

results matching ""

    No results matching ""