Kira Grogg · this is what i do

fb g+ tw pin

Some basic python (a.k.a. cheat sheet)

[Under construction]


Syntax to remember

Python data structures linkout


>>> 2+6  # addition
>>> 2*4  # multiplication
>>> 2**3 # powers

Usual order of operations apply:

>>> 2+4*3
>>> (2+4)*3

Package math makes available more complex functions

>>> import math
        >>> math.log(100,10)


Strings are essentially lists of characters

>>> "this is a string"
'this is a string'
>>> s="this is a string stored in variable 's'."
>>> print s
this is a string stored in variable 's'.

Length of the string:

>>> len(s)

First and last elements of string 's':

>>> s[0], s[-1]
('t', '.')

Concatenate strings:

>>> s + " 's' is " + str(len(s)) + " characters long"
"this is a string stored in variable 's'. 's' is 40 characters long"


Importing modules is a key element of python, either built in modules (os, sys), or those of your own design.

Best practice is to import all modules at the beginning of a script

        import os
        import math
        x = math.log(20)

Also possible is to import all the functions within a module, and avoid including the module name. However, it is usually better to be explicit, since the function might have been redefined at some point, or overwritten by a different module.

        from math import *
        x = log(20)


Define a new function like so:

def myFunction(param1, param2=12, param3=0):
          """ Description of what the function does goes here 
          param1 -- this is an integer...   
          param2 -- this is another integer with default value 12 
          param3 -- this is another integer with default value 0
          results-- also and integer

          result = param1 * param2 + param3
          if(result > 0):
             return result
             return False

Other useful tidbits

Easy swap variables:

>>> a, b = b, a


Script copies files modified in the last -t days into a (hardcoded) backup folder. Not the cleanest script but it does the job.

I use this as a cron job to create daily backups of certain files that have been modified that day.


Lists are generally a collection of similar elements, each dealt with individually. They are mutable, i.e., elements can be added, removed, changed. Can be used as stacks or queues.

>>> list1 = ['a','b','c','d','e','f','g']

To get subset of list starting from 3rd element ('c'):

>>> list1[2:]
['c', 'd', 'e', 'f', 'g']

To get subset of list starting from 3rd to last element ('e'):

>>> list1[-3:]
['e', 'f', 'g']

To copy list to new variable:

>>> list2 = list1[:]

To link (reference) new variable to existing list:

>>> list3 = list1

The difference in the assigments:

>>> list2.append('h')
        >>> print list2
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
>>> print list1
['a', 'b', 'c', 'd', 'e', 'f', 'g']


>>> list3.append('h')
        >>> print list3
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
>>> print list1
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

Make a string out of a list of strings


Make a string out of a list of strings with a delimiter -


Compare beginning or end of string with another string

>>> mystring = "filename.txt"
        >>> mystring.endswith(".txt")

Copy a list

        >>> list4 = list3[:]
        >>> list3[0] = 'apple'
        >>> print list3; print list4
['apple', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

Link to a list (change one list, the other one changes too!)

        >>> list5 = list3
        >>> list3[2] = 'cantaloupe'
        >>> print list3; print list5
['apple', 'b', 'cantaloupe', 'd', 'e', 'f', 'g', 'h']
['apple', 'b', 'cantaloupe', 'd', 'e', 'f', 'g', 'h']

List comprehensions provide a concise way to create and manipulate lists:

>>> squares = [x**2 for x in range(10)]
        >>> print squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Print only even elements of squares

>>> print [x for x in squares if x%2==0]
[0, 4, 16, 36, 64]

Make a list of n of the same item

>>> n = 5
        >>> boring_list = [0]*n
        >>> print boring_list
[0, 0, 0, 0, 0]


Tuples are simple structures of different element types that are related. They are immutable and the order matters. Elements cannot be reassigned.

>>> items = ('Item1','Item2','Item3','Item4','Item5')
>>> items[1]
>>> items[1] = 'differentItem'
TypeError: 'tuple' object does not support item assignment


Unordered collection of elements with no duplicates

>>> list4 = [1,2,3,1,4,6,7,3,2,7,3,2,5,3,1,5,3,4,]
        >>> print set(list4)
set([1, 2, 3, 4, 5, 6, 7])


Maps a set of keys to a set of values. Indexing is done by the key rather than number ranges.

>>> dict1 = {} #empty dictionary

Initialize with key:values

>>> dict1 = {'a':'apple','b':'banana','c':'cantaloupe'}
        >>> dict1['a']

Get list of all keys and list of all values

>>> (dict1.keys(),dict1.values())
(['a', 'c', 'b'], ['apple', 'cantaloupe', 'banana'])

Get the value for a given key, or get a preset default value if key doesn't exist

        >>> dict1.get('a', 'default1')
        >>> dict1.get('d', 'default2')