Introduction to Computer Science

Python Quick Reference

Lists

Creating Lists

Lists are created by putting a comma-separated sequence of expressions in square brackets. For example, [1,2,3] creates a list containing three integers, while ["cat","dog"] creates a list containing two strings. The empty list is created with [].

Accessing a List

Each element in a list has an index: the first element has index 0, the second element has index 1, and so on. We access the elements of a list by indexing. The following code prints "are".

lst = ["How","are","you"]
print lst[1]

Adding to a List

We may add elements to the end of a list with the my_list.append(element) method.

Note that the list is changed to include the new element even though the append method doesn’t return anything.

Files

Opening Files

Use the open(filename,mode) function.

Writing Files

Use the my_file.write(data) method of the file object.

Reading Files

There are several methods to read from a file object.

Reading the whole file.

Use the my_file.read() method.

Reading a single line of the file.

Use the my_file.readline() method.

Note that the line that is returned will usually include the newline character (\n) that ended the line.

Reading each of the lines of a file.

A file object may be used in for loop to get each of the lines in the file. Each time the loop runs, the readline method is called and the result is stored in the loop variable. For instance, the following loop prints the length (including the newline) of each line in a file object my_file:

for line in my_file:
  print len(line)

Closing Files

When you are finished with a file, you should close it with my_file.close(). If you do not do this, the data you wrote to the file may not actually be stored on the computer!