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.
- Parameters:
element
: The element to add to the list.
- Returns:
- Nothing.
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.
- Parameters:
filename
: A string naming the file to open.mode
:"r"
to read the file or"w"
to write a new file.- Note: Using
"w"
will delete any file with the given name to make room for the new file!
- Note: Using
- Returns:
- A value of type
file
which can be used to read from or write to the file.
- A value of type
Writing Files
Use the my_file.write(data)
method of the file
object.
- Parameters:
data
: The string to write to the file. If you want a new line, remember to use the newline character (\n
).
- Returns:
- Nothing.
Reading Files
There are several methods to read from a file
object.
Reading the whole file.
Use the my_file.read()
method.
- Parameters:
- No parameters.
- Returns:
- The string containing the entire file.
Reading a single line of the file.
Use the my_file.readline()
method.
- Parameters:
- No parameters.
- Returns:
- A single line from the file, or
""
if no lines are left.
- A single line from the file, or
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!