15-112 Lecture 4 (Thursday, May 23, 2013)


Lists are ordered, indexable collections. We've seen lists before in the sense that strings are essentially lists of characters. With lists, we can select items by their index number, or range of indexes. We can splice lists together, append items, and remove them.

Let's see some examples:


names = [] # Creates an empty list of names
names = ["Greg", "Dave", "Tom", "Klaus"] # Creates a list of 4 strings

print names    # Prints the whole list
print names[0] # Prints "Greg"
print names[3] # Prints "Klaus"

names[1] = "David"  # Changes names[1] from "Dave" to "David"
print names         # Prints the whole list, as modified

names.insert(2, "Santa Claus") # Inserts a name using insert()
print names                    # Prints the whole list, as modified

names = names[0:2] + ["Easter Bunny"] + names[2:] # Inserts a name by splicing
print names

del names[2]     # Remove an item by the del operator
print names      # print the modified list

names = names[0:2] + names[3:]   # remove and item by splicing
print names                      # print a modified list

names.remove ("Greg")   # Remove an item by seaching for the value
print names             # print a modified list

names.append ("Gregory")   # Add an item via the append method
print names             # print a modified list

names = names[0:] + ["Superman"]
print names             # print a modified list

What are the take-aways?

Lists and the "for loop"

As you might imagine, it is realtively easy to walk through, or traverse, a List with a for loop. But, Python provides an easier way, too. The "for loop" automatically traverses a List, taking one step per iteration, as shown below:


names = ["Greg", "Dave", "Tom"]

# Traversal of a list via a while loop and index variable
index = 0
while (index < len(names)):
  name = names[index]
  print name
  index = index + 1

print ""

# Traversal of a list via a for loop
for name in names:
  print name


What are the take-aways?

For loops, Lists and "range()"

The range() function creates a list of ints within the specified range. The most common use of this, however, is probably not to create a list of numbers for some arbitrary reason -- but instead to provide a pretty way of controlling a loop's iteration.

Consider, for example, the examples below:


oneTo10 = range(1,11) # 1,2,3,4,5,6,7,8,9,10
print oneTo10

negTwoToTen = range(-2,11) # -2,-1,0,1,2,3,4,5,6,7,8,9,10
print negTwoToTen

evens = range (0,11,2) # 0,2,4,6,8,10
print evens

odds = range(1,11,2) # 1,3,5,7,9
print odds

# Print squars of 1 - 10
for number in oneTo10:
  print number*number


What are the take-aways?

For loops and Files

For loops can also be used to iterate through the lines of a file The examples below show this technique:


# This is a fairly understandable case
for line in open("input.txt"):
  print line,

# This is some extra-special kung-fu -- don't worry too much about it
# Wrapping it in []-brakcets makes it a list
# And the "x for x" construct, assigns a value to each iteration
lines = [ line for line in open("input.txt") ]
print lines,

Command-line arguments

You may have noticed that, when you start some programs, you can provide them with inputs as the command line, for example, "ls examples", or "touch example3.py", or "chmod +x example2.py". This is because the operating system loader provides running programs with access to these command-line arguments. In Python it does this via a list, where the 0th argument is the name of the script, itself.

To get access to this functionality, we need to "import" the system module. In other words, we need to ask the Python interpreter to make use of some code that is installed on the system, and organized as a module, but that we didn't write.

Let's see an example:


import sys

if (len (sys.argv) == 1):
  print "Only the name of the program has been provided."
  print "There are " + str(len(sys.argv)) + " arguments, including the name of the script."

print "The name of the script is " + sys.argv[0] + "."

index = 1
while (index < len(sys.argv)):
  print sys.argv[index]
  index = index + 1

for argument in sys.argv:
  print argument


What are the take-aways?


In an abstract sense, tuples are different than lists. But, in practice, as implemented in Python, they are essentially immutable Lists. I don't want to spend a lot of time on them, because that basically sums it up. They work the same way -- except that mutators, such as insert(), remove(), append(), etc, don't exist.

About the only detail worth noting is that they are declared using ()-parenthesis, rather than []-brackets. An example is below:

Let's see an example:


person1 = ("Gregory Kesden", "Faculty", 1999)

print person1[0]
print person1[1]
print person1[2]

print ""

for attribute in person1:
  print attribute



Sets are another type of collection. But, unlike lists and tuples, they are not ordered or indexed. Instead, they are just bags of things. In general, what one does with a set is put things in, take things out, and/or test to see whether or not something or things are members.

Lists were created using []-brackets. Sets were created using ()-parentheses. Sets, oddly, are created using both! Their initial items are listed between ([ and ]). Also, note that, in the example below, the keyword set is required, unlike for lists, tuples, or dictionaries (later).

A single item can be added to a set using add(), a list of items can be added to a set using update(), and a single item can be removed using remove().

There are 4 key binary operations upon sets:

Let's look at an example:


instructors = set (["Greg", "Dave", "Adam", "Jamie", "Kelly"])
faculty = set (["Greg", "Dave", "Cohen", "Kamlet", "Rob"])
gradstudents = set (["Adam", "Jamie", "Kelly", "Richard", "Sarah", "Sam", "Rob"])

print "people"
people = faculty | gradstudents
print people

print ""

print "gradinstructors"
gradinstructors = instructors & gradstudents
print gradinstructors

print ""

print "facultyinstructors"
facultyinstructors = instructors & faculty
print facultyinstructors

print ""

print "gradAndFaculty"
gradAndFaculty = faculty & gradstudents
print gradAndFaculty

print ""


Dictionaries are a very useful collection. They store key-value pairs in the same way that, for example, a dictionary of words and definitions stores definitions associated with their words -- we look up the words to find the definitions.

Dictionaries, as a form of collection, store values indexed by keys. What I mean by "indexed by keys" is finable by looking up the key. Essentially, a Dictionary operates like a List -- except that you can pick the index for each item, rather than being limited to sequential integers.

As an aside, just in case you hear the phrase, in some languages, such as Perl, dictionaries are known as "associative arrays".

Like the syntax for lists used []-brackets, and tuples ()-parenthesis, dictionaries use {}-squiggly-brakcets.

Let's look at an example:


offices = {
  "Greg" : "GHC 7711",
  "Tom" : "GHC 4117",
  "Dave" : "GHC 5001"

# Look up a single name
print "Greg's office is " + offices["Greg"]
print "Tom's office is " + offices["Tom"]

# Convert the Dictionary to a list, to get a list of keys
keys = list(offices)
for name in keys:
  print name

# Iterate through the list to get the values
for name in keys:
  print offices[name]

# Remove Greg's entry
print offices
del offices["Greg"]
print offices

# Add a new entry
offices["Gregory"] = "GCH 7711"
print offices

Some things to note: