Skip to content
Rochelle Terman edited this page May 9, 2016 · 17 revisions

Table of Contents

External Cheat Sheets

  1. Python 2.7 Quick Reference Sheet
  2. Dave Child's Python cheatsheet

Also check out our list of resources here

1. Types and common operators / functions

  • a in b: Test whether a is contained in b and returns True if so. b can be a string, list, tuple, set or dictionary.

  • a not in b: Returns True ir a is NOT contained in b. b can be a string, list, tuple, set or dictionary.

  • type(obj): Returns the data type of an obj.

  • str(obj): Returns a string representation of an obj, i.e. obj coerced to a string

  • int(obj): Returns an integer representation of an obj, i.e. obj coerced to an integer

  • float(obj): Returns a float representation of an obj, i.e. obj coerced to an float

  • len(seq): Returns the number of items in a sequence seq: a sequence can be a string, list, tuple, etc.

  • range(int): Returns a sequences of integers from 0 to int-1.

  • range(start, end, by): Returns a sequences of integers from start to end-1, in steps of by.

> range(4, 10, 2)
4, 6, 8

2. Strings

  • string[index1 : index2]: Slices a string from index1 to index2 (excluding index2)

  • string.upper(): Makes a string all uppercase.

> s = "donut"
> s.upper()
DONUT
  • string.lowercase(): Makes a string all lowercase.

  • string.join(list): Concatenates each item in list with the delimiter string.

> l = ["Billy", "Bob", "Thorton"]
> "".join(l)
"BillyBobThorton"
> "--".join(l)
"Billy--Bob--Thorton"
  • string1.startswith(string2): Returns True if string1 starts with string2, False otherwise.

  • string1.endswith(string2): Returns True if string1 ends with string2, False otherwise.

  • substring in string: Returns True if substring is contained in string, False otherwise.

3. Lists

  • list[index]: Finds the item in list with the position index.

  • list[index1 : index2]: Slices a list from index1 to index2 (excluding index2)

  • list.append(obj): Appends obj to the end of list

  • list.extend(obj): Extends list to include obj, which is usually another list.

  • list.index(obj): Returns index of first occurrence of obj in list; raises ValueError if obj not in list.

  • list.remove(obj): Removes first instance of obj in list; raises ValueError if obj not in list.

  • list.sort(): Sorts list in order, in place.

  • list.count(obj): Returns an integer counting the number of occurrences of obj in list

  • obj in list: Returns True if obt is contained in list, False otherwise.

4. Dictionaries

  • dict[key]: Returns the value paired with key in dict. key is usually a string. Can also be used in assignment:
> dict = {} # make empty dictionary
> dict['name'] = 'Barack Obama' # assign a key / value pair to `dict`
> dict['name'] # lookup
'Barack Obama'
  • key in dict: Returns True if dict contains key, False otherwise.

  • dict.keys(): Returns a list of dict's keys.

  • dict.values(): Returns a list of dict`'s values.

  • dict.items(): Returns a list of key / value pairs in dict`. Each list item is a 2 item tuple.

5. Conditionals

  • Conditional syntax:
> if (boolean_exp):
     do something
> elif (boolean_exp):
     do something
> else:
     do another thing
  • Boolean operators: and, or, not
> if (boolean_exp) and (boolean_exp):
    do something

6. Functions

  • define function
> def function_name(arg1, arg2):
     answer = arg1 + arg2
     return(answer)
  • call function
> function_name(2, 3)
5

7. Loops

  • for loops:
> for item in list:
      do something
  • alter every item in a list, and store those values in another list:
> orig_list = [1, 2, 3] # make list to iterate over
> stored = [] # make empty list to store new values

> for item in orig_list:
      new_item = item + 2 # do something to each item, here we add 2
      stored.append(new_item) # store that new item in the `stored` list.

> stored
[3, 4, 5]
  • alter every item in a list and store those values in the same list
> for index in range(len(orig_list)): # iterate over indices
      orig_list[index] = orig_list[index] + 2

> orig_list
[3, 4, 5]
  • iterate over indices + values at the same time using multiple iteration
> fruit = ['apples', 'bananas', 'kiwis']

> for val, index in enumerate(fruit):
      print val, index

0 'apples'
1 'bananas'
2 'kiwis'

8. Files

  • Read contents of file example.txt into variable text
> with open('example.txt') as my_file:
      text = my_file.read()
  • Read in a file line by line, storing those lines as a list
> stored = [] # create empty list to store lines
> with open('example.txt') as my_file:
     for line in my_file:
         stored.append(line.strip()) # line.strip() will get rid of line breaks characters.
  • Write a list to a file, with each item on its own line.
bees = ['bears', 'beets', 'Battlestar Galactica']
with open('example.txt', 'w') as new_file:
    for i in bees:
        new_file.write(i + '\n') # will write each item on its own line
  • Read in a CSV as a list of dictionaries, with each dictionary representing a row and keys representing columns.
> stored = [] # make empty list to store dictionaries
> with open('example.csv', 'rU') as csvfile: # open file
     reader = csv.DictReader(csvfile) # create a reader
     for row in reader: # loop through rows
         stored.append(row) # append each row to the list
  • Write list of dictionaries as a CSV (note that each dictionary must have the same keys!)
> keys = stored[0].keys() # get a list of the keys, which will be column names.
> with open('example.csv', 'wb') as output_file:
     dict_writer = csv.DictWriter(output_file, keys)
     dict_writer.writeheader()
     dict_writer.writerows(stored)