Syntax Examples

Lecture 02:

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])
  • creates a list of integers [start, start + step * 1, ..., start + step * i] such that start + step * i < stop if step is postive and start + step * i > stop if step is negative. If not specified, start is zero.

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

Lecture 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:

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:

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]
my_list.append(8) # [2,4,8]
print my_list[0] # access the first element of a list

Lecture 06:

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.

num_vals = 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:

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:

my_data = set() # creates an empty set, do not use {} for empty set
some_data = set([1, 2, 3, 'some', 'stuff'])
other_data = {'one_pt', 'another_pt'}  

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([]) # creates an empty 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    # this might print: set(['play', 'sleep', 'study', 'eat'])

my_plan.discard('play')    # this would be o.k. even if 'play' wasn't in set
print my_plan    # Assuming my_plan from above, this prints: set(['sleep', 'study', 'eat'])

my_plan = my_plan - {'sleep'}    # this would be o.k. even if  'sleep' wasn't in set
print my_plan                # this prints: set(['study', 'eat'])

my_plan.remove('eat')    # this would be an error 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 = {3, 4, 5, 6}
data |= other_data  # same as: data = 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: Dictionaries

Making a dictionary

A dictionary is an unordered mapping of keys to values.

  • Keys must be unique. No duplicates.
  • Keys must be immutable so int, float, and string types are ok but not a list, set, or dict types.
  • Dictionaries are mutable so key -> value mappings can be added, removed or replaced.

To create a dictionary:

empty_dict = {}
days_dict = {"sun":18, "sat":20, "mon":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['sun']  # prints 18

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

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

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

print days_dict.get('tues', 0)  # prints 0
print days_dict.get('mon', 0)   # prints 17

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

'tues' in days_dict     # evaluates to False
days_dict.has_key('sat')    # 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['tues'] = 8
# days_dict is now: {'sun':18, 'tues':8, 'sat':20, 'mon':17}
days_dict.update({'wed':10, 'thurs':7, 'fri':26})
# days_dict is now: {'sun':18, 'mon':17, 'tues':8, 'fri':26, 'wed':10, 'sat':20, 'thurs':7}

Changing an element in a dictionary

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

days_dict['sun'] = 17
# days_dict is now: {'sun':17, 'mon':17, 'tues':8, 'fri':26, 'wed':10, 'sat':20, 'thurs':7}
days_dict['sat'] += 2
# days_dict is now: {'sun':17, 'mon':17, 'tues':8, 'fri':26, 'wed':10, 'sat':22, 'thurs':7}

Removing an element from a dictionary

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

del days_dict['sun']
# days_dict is now: {'mon':17, 'tues':8, 'fri':26, 'wed':10, 'sat':22, 'thurs':7}

Iterating through a dictionary

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

for day in days_dict.keys():
  print day, days_dict[day]
# Prints (order not guaranteed):
thurs 7
mon 17
wed 10
fri 26
tues 8
sat 22

for count in days_dict.values():
  print count
# Prints (order not guaranteed):
7
17
10
26
8
22

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

for day in days_dict:
  print day, days_dict[day]
# Prints (order not guaranteed):
thurs 7
mon 17
wed 10
fri 26
tues 8
sat 22

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
# Prints (order not guaranteed):
thurs 7
mon 17
wed 10
fri 26
tues 8
sat 22

Lecture 9:

Sorting

There are two simple ways to sort a list. For either way, 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. Does not modify the original list. (Note: see discussion of tuples and itemgetter later in this document.)

from operator import itemgetter

students = [('jane', 'B', 12), ('john', 'A', 15), ('dave', 'B', 10)]

sorted_by_letter = sorted(students, key=itemgetter(1))

print students
# [('jane', 'B', 12), ('john', 'A', 15), ('dave', 'B', 10)]

print sorted_by_letter
# [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
# Note that when there is a tie, the original order is maintained,
# in this case that means 'jane' comes before 'dave' because 'jane' comes
# before 'dave' in the original order.
# This behavior is called a "stable" sort.  Not all sorting algorithms
# are stable, but Python's sort() and sorted() are.

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] # Prints: 1
print my_tuple[1] # Prints: two
print my_tuple[2] # Prints: 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_name is now just another name for the function itemgetter(0)
get_score = itemgetter(1) # get_score is now just another name for the function itemgetter(1)

name = get_name(student_score)   # name is now 'Robert'
score = get_score(student_score) # score is now 8

student_scores = [('Robert', 8), ('Alice', 9), ('Tina', 7)]

# sort the list of student scores by student name
sorted_by_name = sorted(student_scores, key=get_name)
print sorted_by_name 
# Prints: [('Alice', 9), ('Robert', 8), ('Tina', 7)]

# sort the list of student scores by student name, but in reverse
reverse_sorted_by_name = sorted(student_scores, key=get_name, reverse=True)
print reverse_sorted_by_name 
# Prints: [('Tina', 7), ('Robert', 8), ('Alice', 9)]

# sort the list of student scores by the students' scores
sorted_by_score = sorted(student_scores, key=itemgetter(1))
# OR sorted_by_score = sorted(student_scores, key=get_score)
print sorted_by_score
# Prints: [('Tina', 7), ('Robert', 8), ('Alice', 9)]

# sort by letter grade, and then by numeric score if there is a tie
students = [('jane', 'B', 12), ('john', 'A', 15), ('dave', 'B', 10)]
sorted_by_letter_then_score = sorted(students, key=itemgetter(1, 2))
print sorted_by_letter_then_score
# Prints: [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

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