Introduction to Computer Science
CompSci 101 : Fall 2013

Python Summary

This page lists Python types, functions, and operators that have been covered in class. The online Python References are linked for each sections and provide more complete coverage.
Mathematical Operators
Symbol Meaning Example
+ addition 4 + 5 is 9
- subtraction 9 - 5 is 4
* multiplication 3 * 5 is 15
/ division 6/3 is 2
6/4 is 1
6.0/4 is 1.5
% mod/remainder 5 % 3 is 2
** exponentiation 3**2 is 9
2**3 is 8
Sequence Operators
+ concatenation "ab" + "cd" is "abcd"
[1,2] + [3,4] is [1,2,3,4]
* repeat "xo" * 3 is "xoxoxo"
[0] * 3 is [0,0,0]
[] indexing
note, indexing starts from 0 and negative values can be used to index from the sequence's end
"ab"[1] is "b"
[1,2,3,4][-1] is [4]
[start:end] slicing from start up to but not including end
note, if start is left off, 0 is assumed and if end is left off, len(sequence) is assumed
"abcd"[1:3] is "bc"
"abcd"[:-2] is "ab"
[1,2,3,4][:] is [1,2,3,4]
[start:end:stride] slicing with stride
note, if stride is negative, the elements of the sequence are accessed in reverse order
"abcd"[::2] is "ac"
"abcd"[::-2] is "db"
[1,2,3,4,5][1:-1:2] is [2,4]
in membership "a" in "abcd" is True
"ad" in "abcd" is False
5 not in [1,2,3,4] is True
Comparison Operators
== is equal to 3 == 3 is True
!= is not equal to 3 != 3 is False
>= is greater than or equal to 4 >= 3 is True
<= is less than or equal to 4 <= 3 is False
> is strictly greater than 4 > 3 is True
< is strictly less than 3 < 3 is False
Boolean Operators
x = 5
or returns True if at least one part of it is True (x < 3 or x > 7) is False
(x < 3 or x < 7) is True
and returns True only if both parts of it are True (x > 3 and x < 7) is True
(x > 3 and x > 7) is False
not flips the value of a boolean(not x == 5) is False
is returns True only if the two things being compared are the same thing

x = 5
y = x
(x is y) is True

Type Conversion Functions
int(x) turn x into an integer value
note, this can fail, e.g., int("abc") raises an error
int("123") is 123
float(x) turn x into an float value
note, this can fail, e.g., float("abc") raises an error
float("2.46") is 2.46
str(x) turn x into a string value str(432) is "432"
list(x) turn x into a list value
note, this can fail, e.g., list(123) raises an error
list("abc") is ["a", "b", "c"]
type(x) the type of x type(1) is int
type(1.2) is float
String Functions
s = "colorful"
Name Returns Example
.find(str) index of first occurrence s.find("o") is 1
s.find("e") is -1
.count(str) number of occurrences s.count("o") is 2
s.count("r") is 1
s.count("e") is 0
.strip() copy with leading/trailing whitespace removed "   big ".strip() is "big"
.split() returns list of "words" in s "big bad dog".split() is ["big","bad", "dog"]
.split(seperater) returns list of "items" in s that are separated by a seperater "this,old,man".split(",") is ["this", "old", "man"]
In general split and strip take any string value, not just whitespace or comma, e.g., s.split(":") will split on a colon and s.strip("gat") will remove leading and trailing letters "g", "a", or "t".
.startswith(prefix) boolean if starts with given string s.startswith("color") is True
s.startswith("cool") is False
.endswith(suffix) boolean if ends with given string s.endswith("ful") is True
s.endswith("fool") is False
.lower() string with all lowercase letters s.upper() is "colorful"
.upper() string with all uppercase letters s.upper() is "COLORFUL"
List Functions
l = [2,4,6,2,8,2,10]
Name Returns Example
sum(lst) returns sum of numeric items sum([1,2,4]) is 7
.index(item) index of first occurrence l.index(6) is 2
l.index(7) is -1
.count(item) number of occurrences l.count(2) is 3
l.count(10) is 1
l.count(7) is 0
.insert(index, item) add to list at at position index l.insert(0, 7) is [7,2,4,6,2,8,2,10]
l.insert(-1, 7) is [2,4,6,2,8,2,7,10]
.append(item) add to list's end l.append(7) is [2,4,6,2,8,2,10,7]
.pop(index) remove and return element at position index in list
default index is last value
l.pop(2) is 6, l is now [2,4,2,8,2,10]
l.pop() is 10, l is now [2,4,6,2,8,2]
.remove(item) remove first occurrence l.remove(2) is [4,6,2,8,2,10]
Set Functions
s = set([1,3,5,7,9]), t = set([2,4,5,6,8])
.add(item) adds the item into the set, returns nothing s.add(2) is set([1,2,3,5,7,9])
.union(t) returns set containing all elements in either s OR t, t can be any sequence s.union(t) is set([1,2,3,4,5,6,7,8,9])
.intersection(t) returns set containing only elements in both s AND t, t can be any sequence s.intersection(t) is set([5])
.difference(t)

returns set containing only elements in s NOT t, t can be any sequence

s.difference(t) is set([1,3,7,9])
s | t returns union of s and t, both must be sets (s | t) is set([1,2,3,4,5,6,7,8,9])
s & t returns intersection of s and t, both must be sets (s & t) is set([5])
s - t returns difference between s and t, all elements in s that are not in t (s - t) is set([1,3,7,9])
Dictionary Functions
d = {"one": 1, "two": 2, "three": 3}
d[key] returns value associated with key, error if key not in dictionary d d["one"] is 1
d["four"] is an error
d.get(key) returns value associated with key, error if key not in dictionary d d.get("one") is 1
d.get("four") is an error
d.get(key, default) returns value associated with key, returns default if key not in d d.get("one",0) is 1
d.get("four",0) is 0
d.keys() returns list of the keys in dictionary d.keys() is ["one","two","three"]
d.values() returns list of the values in dictionary d.values() is [1,2,3]
d.items() returns list of tuples, (key, item) pairs from dictionary d.items() is [("one",2),("two",2),("three",3)]
General Functions
abs(x) returns absolute value of the int or float x abs(-33) is 33
abs(-33.5) is 33.5
len(x) returns length of sequence x len("duke") is 4
range(x) returns list of integers starting at 0 and going up to but not including x range(5) is [0,1,2,3,4]
range(start, stop) returns list of integers starting at start and going up to but not including stop range(3, 7) is [3,4,5,6]
sorted(x) returns list that is sorted version of sequence x,
does not change x
sorted("cat") is ["a","c","t"]
min(x, y, z) returns minimum value of all arguments min(3, 1, 2) is 1
min("z", "b", "a") is "a"
max(x, y, z) returns maximum value of all arguments max(3, 1, 2) is 3
max("z", "b", "a") is "z"
In general, min and max take any sequence, e.g., a list or a string.
help(x) documentation for module x  
Regular Expression Pattern Power Characters (import re)
\d match any digit, equivalent to [0-9] '\d' matches '0', but not 'a'
\w match any "word" character, i.e., letter, digit, or underbar: equivalent to [a-zA-Z0-9_] '\w' matches 'a' or '_', but not '+'
. match any kind of character '...' matches any three characters
^ match at the start of the pattern '^x' matches any text that starts with an x
$ match at the end of the pattern 'x$' matches any text that ends with an x
+ match 1 or more occurrences of the pattern to its left 'i+' matches 'igloo' and 'radii',
but not 'apple'
* match 0 or more occurrences of the pattern to its left '\d*.\d' matches '10.1' and '.9',
but not 'a.b'
[] match any of the included characters '[aeiou]' matches any vowel
'[0-9]' matches any digit
? match 0 or 1 occurrences of the pattern to its left '0?1' matches '101' and '11', but not '1001'

Regular Expression Functions (import re)

re.sub(pattern, replacement, text) find all substrings in given string where the pattern matches and replaces them with replacement string
re.findall(pattern,text) find all substrings in given string where pattern matches, returns them as a list
re.search(pattern, text) find all locations in given string where pattern matches, returns match object, MAT, or None
File Functions
open(path) create file object from given file on disk open("data.txt")
open("c:\data\numbers.txt")
.read() read entire contexts of file into string  
.readlines() read entire contents of file into list of strings separated by newline, each string includes newline  
.close() closes file, no longer possible to read from file