Lecture 02: 04-01

For loop syntax for iterating over a sequence

for i in sequence:
    #for loop block 
    print i

Official Python documentation: https://docs.python.org/2/tutorial/controlflow.html#for-statements

The range function quickly creates sequential lists

range(start,stop[,step])

Official Python documentation: https://docs.python.org/2/library/functions.html#range

Lecture 03: 04-03

If statement syntax for conditional branching

Conditions must evaluate to a boolean (true or false) result. For example: x == 5

if condition:
    #if block 
    print "if condition was true"

Optional Elif or Else for additional branch options

You can include zero or more elif statements and zero or one else statements.

if condition1:
    #if block 
    print "if condition1 was true"
elif condition2:
    #elif block 2 
    print "elif condition2 was true"
elif condition3:
    #elif block 3 
    print "elif condition3 was true"
else:
    #else block 
    print "elif condition3 was true"

Official Python documentation: https://docs.python.org/2/tutorial/controlflow.html#if-statements

Lecture 04: 04-06

Defining functions

Functions allow you to perform the same action without copying code by simply calling the function.

def function_here(input_things):
    """Description of function goes here"""
    #performs actions here 
    manipulated_input = input_things*2
    #returns the following to be used in the code that calls this function 
    return manipulated_input

Official Python documentation: https://docs.python.org/2/tutorial/controlflow.html#defining-functions

Lecture 05: 04-08

Lists

The list data structure is a mutable sequence type created with square brackets.

my_list = []  #empty list 
my_list.append(2) #[2] 
my_list.append(4) #[2,4,8] 
my_list.append(8) #[2,4,8] 
print my_list[0] #access the first element of a list 

Lecture 06: 04-10

More About Lists

Assigning List Elements

List elements can be assigned and reassigned singly:

my_list = [1, 2, 3, 4] #[1,2,3,4] 
my_list[3] = "at index 3" #[1,2,3,"at index 3"] 

Or as a slice:

my_list[1:3] = ["at index 1", "at index 2"] #[1, 'at index 1', 'at index 2', 'at index 3'] 

Slices

Creates a new list from a range (two indices) of elements in the original list. The start index is inclusive, the end index is exclusive.

new_list = original_list[start : end]

in

Evaluates to True if val is in the list, False if it is not.

contains = val in my_list

Official Python documentation: https://docs.python.org/2/library/stdtypes.html#typesseq

index

Find the index of the first occurrence of val in a list. It is an error if val is not in the list.

i = my_list.index(val)

count

Counts the number of times a value appears in a list.

cnt = my_list.count(val)

remove

Removes the first occurrence of a value from a list.

my_list.remove(val)

pop

Removes and returns the last element from a list.

last = my_list.pop()

Official Python documentation: https://docs.python.org/2/tutorial/datastructures.html#more-on-lists

Lecture 07: 04-13

Making a set

Sets are a valuable type because you can easily manipulate them and they have no repeated items. Keep in mind this data structure is not ordered though, meaning the data you enter will not stay in the order you enter it.

To create a set:

some_data = set([1, 2, 3, 'some', 'stuff'])
other_data = {'one_pt''another_pt'}  #there must be elements in the curly brackets, {} means something else 

Official Python documentation: https://docs.python.org/2/library/stdtypes.html#set

Add an element to a set

This will add an element to your set. Remember, the order in which you add is irrelevant!

books = set([])
books.add('Quidditch Through the Ages')
print books    #this prints: set(['Quidditch Through the Ages']) 

Remove an element from a set

There are several different ways to remove an element from a set.

my_plan = {'eat''sleep''study''play''work'}
 
my_plan.pop()    #this will choose and remove one arbitrary element 
print my_plan     #here, this prints: set(['play', 'sleep', 'study', 'eat']) 
 
my_plan.discard('play')    #this would work even if 'play' wasn't in set 
print my_plan    #this prints: set(['sleep', 'study', 'eat']) 
 
my_plan = my_plan - {'sleep'}    #this would work even if  'sleep' wasn't in set 
print my_plan    #this prints: set(['study', 'eat']) 
 
my_plan.remove('eat')    #this would NOT work if  'eat' wasn't in set, KeyError 
print my_plan    #this prints: set(['study']) 

Membership

Identify if something is in your current set.

books = {'Lord of the Rings''The Book Thief''Quidditch Through the Ages'}
'Star Wars' in books              #evaluates as False 
'Lord of the Rings' in books  #evaluates as True 

Union

Update your current set by adding the new elements from other sets.

data = set([1, 2, 3, 4])
other_data = {3456}
data |= other_data
print data  #this yields the output: set([1, 2, 3, 4, 5, 6]) 

Intersection

Identify what elements sets have in common.

my_music = {'classical''rock''jazz'}
cafe_music = {'jazz''blues''hipster'}
shared_music = my_music & cafe_music
print shared_music   #this prints: set(['jazz']} 

Difference

Identify what elements are not in one set when compared to another.

my_music = {'classical''rock''jazz'}
cafe_music = {'jazz''blues''hipster'}
 
unique_to_me =  my_music - cafe_music
print unique_to_me     #this prints: set(['classical', 'rock']) 
 
unique_to_cafe =  cafe_music - my_music
print unique_to_cafe   #this prints: set(['blues', 'hipster']) 

Lecture 8: 04-15 Dictionaries

Making a dictionary

A dictionary is an unordered mapping of keys to values.

To create a dictionary:

empty_dict = {}
days_dict = {"sunday":18, "saturday":20, "monday":17}
dict_of_lists = { 
  'Sounders':[1,0,0,1,0,1,1,1,0,1,1], 
  'SeaHawks':[1,1,1,1,1,1,1,1,1,1,1,0], 
  'Mariners':[0,1,1,1,1,1,0,1,0,0,1,1,0,1,1,1,0,0], 
}

Accessing an element from a dictionary

Values from a dictionary can be retrieved using the key.

print days_dict['sunday']  #prints 18 

But trying to access a key that does not exist will cause an error.

print days_dict['tuesday']  #throws KeyError: tuesday 

However you can use the dictionary method get to provide a default value.

print days_dict.get('tuesday',0)  #prints 0 
print days_dict.get('monday',0) #prints 17 

You can also test if a key is in a dictionary.

'tuesday' in days_dict #evaluates to false 
days_dict.has_key('saturday') #evaluates to true 

Adding to a dictionary

To add to a dictionary assign to a key that does not exist. Or use the update method.

days_dict['tuesday'] = 8
days_dict.update({'wednesay':10, 'thursday':7, 'friday':26})

Changing an element in a dictionary

Assigning to a key already in a dictionary changes the mapping.

days_dict['sunday'] = 17
days_dict['saturday'] += 2

Removing an element from a dictionary

To remove an element from a dictionary use the del keyword.

del days_dict['sunday']

Iterating through a dictionary

Use the keys() and values() iterate through a dictionary.

for day in days_dict.items():
  print daydays_dict[day]
 
for count in days_dict.values():
  print count

Shortcut 1: Iterating through a dictionary is equivalent to using the keys() method.

for day in days_dict:
  print day,days_dict[day]

Shortcut 2: Use the items() method to iterate through key,value pairs at the same time.

for day,count in days_dict.items():
  print day,count

Lecture 9: 04-17

Sorting

There are two simple ways to sort a list. For either you can provide functions for comparison, key finding, and can supply a boolean to specify if the sort should be reversed.

my_list.sort()

Modifies the existing list. Returns None.

my_list = [100, 200, 0, -100]
 
my_list.sort() # my_list is now sorted [-100, 0, 100, 200] 
my_list.sort(reverse = True) # my_list is now reverse sorted [200, 100, 0, -100] 

Official Python documentation: https://docs.python.org/2/tutorial/datastructures.html#more-on-lists

sorted(my_list)

Returns a new copy of the list that has been sorted.

students = [('jane''B'12), ('john''A'15), ('dave''B'10)]
 
sorted_students = sorted(studentskey=itemgetter(1,2))
 
print students
# [('jane', 'B', 12), ('john', 'A', 15), ('dave', 'B', 10)] 
 
print sorted_students
# [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)] 

Official Python documentation: https://docs.python.org/2/library/functions.html#sorted

Lecture 11: 04-22

Tuples

An immutable ordered sequence of values. You can create new tuples, access individual elements but cannot change the elements in an existing tuple.

Create new Tuples

Tuples are created using parenthesis and by separating the elements with commas.

my_tuple = (1, 'two' 3)

Access

You can access elements of a tuple in the same way you access elements of a list.

my_tuple = (1, 'two' 3)
print my_tuple[0] # 1
print my_tuple[1] # two
print my_tuple[2] # 3

Official Python documentation: https://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences

itemgetter

Itemgetter is a function that returns a function. Use it to make functions that are used to get elements from a tuple. This can be useful when supplying a key function to a sort.

from operator import itemgetter
 
student_score= ('Robert'8)
get_name = itemgetter(0)
get_score = itemgetter(1)
 
get_name(student_score) # evaluates to 'Robert' 
get_score(student_score) # evaluates to 8 
 
student_scores = [('Robert'8), ('Alice'9), ('Tina'7)]
 
# sort the list of student scores by the students name 
# [('Alice', 9), ('Robert', 8), ('Tina', 7)] 
sorted_student_scores = sorted(student_scoreskey=get_name)

Official Python documentation: https://docs.python.org/2/library/operator.html#operator.itemgetter