Introduction to Computer Science
CompSci 101 : Spring 2014

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
A shorthand version of each of these exists to update a variable that appears on both sides of the assignment. For example, the statement: x = x + 1 can be shortened to: x += 1 x = 1 sets x to 1
x += 1 sets x to 2
x *= 2 sets x to 4
x **= 2 sets x to 16
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"]
set(x) turn x into a set value
note, this can fail, e.g., set(123) raises an error
set("hello") is set(["h", "e", "l", "o"]
dict(x) turn x into a dict value
note, x must be a sequence of items with 2 elements
dict([("a",2), ("b",4)]) is {"a":2, "b":4}
type(x) returns the type of x type(1) is int
type(1.2) is float
String Functions
s = "colorful"
Name Returns Example
.find(str) returns index of first occurrence of str in s s.find("o") is 1
s.find("e") is -1
.count(str) returns number of occurrences of str in s s.count("o") is 2
s.count("r") is 1
s.count("e") is 0
.strip() returns copy of s with leading and 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".
.join(sequence) returns all strings in sequence joined together with each separated by s ",".join(["this", "old", "man"]) is "this,old,man"
" ".join(["big","bad", "dog"]) is "big bad dog"
.lower() returns string with all lowercase letters s.upper() is "colorful"
.upper() returns string with all uppercase letters s.upper() is "COLORFUL"
.startswith(prefix) returns True only if starts with given string s.startswith("color") is True
s.startswith("cool") is False
.endswith(suffix) returns True only if ends with given string s.endswith("ful") is True
s.endswith("fool") is False
.isalpha() returns True only if all characters are alphabetic s.isalpha() is True
"123".isalpha() is False
.isdigit() returns True only if all characters are digits s.isdigit() is False
"123".isalpha() is True
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
zip(lstA,lstB) returns list of tuples created from corresponding items in each list zip([1,2,4], [1,3,5]) is [(1,1), (2,3), (4,5)]
enumerate(lst) returns list of tuples created from the index and value of items in given list enumerate([1,2,4]) is [(0,1), (1,2), (2,4)]
.index(item) returns index of first occurrence l.index(6) is 2
l.index(7) is -1
.count(item) returns 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]
.extend(lst) add every element of lst to list's end l.extend([8,9]) is [2,4,6,2,8,2,10,8,9]
.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 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"]
Note, sorted takes an optional parameter, reverse=True, which reverses the order of the resulting list sorted("cat", reverse=True) is ["t", "c", "a"]
sorted(x,key=func) returns list that is sorted version of sequence x, according to the given function,
does not change x
sorted(["abc","z"],key=len) is ["z","abc"]
sorted("cat", key=len,reverse=True) is ["abc", "z"]
Note, a popular function to use as a key is itemgetter, which returns the items associated with the given indices of the sub-list (assumming the elements of the list being sorted are sequences themselves). itemgetter(1)[2,4,6] is 4
itemgetter(2,1,0)[2,4,6] is (6,4,2)
sorted(["cat","dog","bear"], key=itemgetter(1)) is ["cat","bear","dog"]
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) prints documentation for module x  
Random Functions
random.choice(lst) returns a random element from lst, error if len(lst) == 0
random.randint(start, end) returns a random integer between start and end
Note, unlike range() and list slicing, the largest value it can return is end, not end-1
random.random() returns a random float between 0 and 1
File Functions
open(path) create file object from given file on disk open("data.txt")
open("c:\data\numbers.txt")
.read() returns string that represents the entire contents of file  
.readlines() returns list of strings that is the entire contents of file separated by newline
note, each string includes newline
 
.close() closes file, no longer possible to read from file  
Special "Escaped" Characters
'\t' tab  
'\n' new line  
'\\' back slash