[TOC]
Python 2.7 Quick Reference https://github.com/justmarkham/python-reference
By Kevin Markham (kevin@dataschool.io)
import math
math.sqrt(25)
from math import sqrt
sqrt(25) # no longer have to reference the module
from math import cos, floor
from os import *
import numpy as np
dir(math)
type(2) # returns 'int'
type(2.0) # returns 'float'
type('two') # returns 'str'
type(True) # returns 'bool'
type(None) # returns 'NoneType'
isinstance(2.0, int) # returns False
isinstance(2.0, (int, float)) # returns True
float(2)
int(2.9)
str(2.9)
bool(0)
bool(None)
bool('') # empty string
bool([]) # empty list
bool({}) # empty dictionary
bool(2)
bool('two')
bool([2])
10 + 4 # add (returns 14)
10 - 4 # subtract (returns 6)
10 * 4 # multiply (returns 40)
10 ** 4 # exponent (returns 10000)
10 / 4 # divide (returns 2 because both types are 'int')
10 / float(4) # divide (returns 2.5)
5 % 4 # modulo (returns 1) - also known as the remainder
from __future__ import division
10 / 4 # true division (returns 2.5)
10 // 4 # floor division (returns 2)
5 > 3
5 >= 3
5 != 3
5 == 5
5 > 3 and 6 > 3
5 > 3 or 5 < 3
not False
False or not False and True # evaluation order: not, and, or
if x > 0:
print 'positive'
if x > 0:
print 'positive'
else:
print 'zero or negative'
if x > 0:
print 'positive'
elif x == 0:
print 'zero'
else:
print 'negative'
if x > 0: print 'positive'
'positive' if x > 0 else 'zero or negative'
empty_list = []
empty_list = list()
simpsons = ['homer', 'marge', 'bart']
simpsons[0] # print element 0 ('homer') len(simpsons) # returns the length (3)
simpsons.append('lisa') # append element to end simpsons.extend(['itchy', 'scratchy']) # append multiple elements to end simpsons.insert(0, 'maggie') # insert element at index 0 (shifts everything right) simpsons.remove('bart') # searches for first instance and removes it simpsons.pop(0) # removes element 0 and returns it del simpsons[0] # removes element 0 (does not return it) simpsons[0] = 'krusty' # replace element 0
neighbors = simpsons + ['ned','rod','todd']
simpsons.count('lisa') # counts the number of instances simpsons.index('itchy') # returns index of first instance
weekdays = ['mon','tues','wed','thurs','fri'] weekdays[0] # element 0 weekdays[0:3] # elements 0, 1, 2 weekdays[:3] # elements 0, 1, 2 weekdays[3:] # elements 3, 4 weekdays[-1] # last element (element 4) weekdays[::2] # every 2nd element (0, 2, 4) weekdays[::-1] # backwards (4, 3, 2, 1, 0)
list(reversed(weekdays))
simpsons.sort() simpsons.sort(reverse=True) # sort in reverse simpsons.sort(key=len) # sort by a key
sorted(simpsons) sorted(simpsons, reverse=True) sorted(simpsons, key=len)
num = [10, 20, 40, 50] from bisect import insort insort(num, 30)
same_num = num same_num[0] = 0 # modifies both 'num' and 'same_num'
new_num = num[:] new_num = list(num)
id(num) == id(same_num) # returns True id(num) == id(new_num) # returns False num is same_num # returns True num is new_num # returns False num == same_num # returns True num == new_num # returns True (their contents are equivalent)
digits = (0, 1, 'two') # create a tuple directly digits = tuple([0, 1, 'two']) # create a tuple from a list zero = (0,) # trailing comma is required to indicate it's a tuple
digits[2] # returns 'two' len(digits) # returns 3 digits.count(0) # counts the number of instances of that value (1) digits.index(1) # returns the index of the first instance of that value (1)
digits[2] = 2 # throws an error
digits = digits + (3, 4)
(3, 4) * 2 # returns (3, 4, 3, 4)
tens = [(20, 60), (10, 40), (20, 30)] sorted(tens) # sorts by first element in tuple, then second element # returns [(10, 40), (20, 30), (20, 60)]
bart = ('male', 10, 'simpson') # create a tuple (sex, age, surname) = bart # assign three values at once
s = str(42) # convert another data type into a string s = 'I like you'
s[0] # returns 'I' len(s) # returns 10
s[:6] # returns 'I like' s[7:] # returns 'you' s[-1] # returns 'u'
s.lower() # returns 'i like you' s.upper() # returns 'I LIKE YOU' s.startswith('I') # returns True s.endswith('you') # returns True s.isdigit() # returns False (returns True if every character in the string is a digit) s.find('like') # returns index of first occurrence (2), but doesn't support regex s.find('hate') # returns -1 since not found s.replace('like','love') # replaces all instances of 'like' with 'love'
s.split(' ') # returns ['I','like','you'] s.split() # same thing s2 = 'a, an, the' s2.split(',') # returns ['a',' an',' the']
stooges = ['larry','curly','moe'] ' '.join(stooges) # returns 'larry curly moe'
s3 = 'The meaning of life is' s4 = '42' s3 + ' ' + s4 # returns 'The meaning of life is 42' s3 + ' ' + str(42) # same thing
s5 = ' ham and cheese ' s5.strip() # returns 'ham and cheese'
'raining %s and %s' % ('cats','dogs') # old way 'raining {} and {}'.format('cats','dogs') # new way 'raining {arg1} and {arg2}'.format(arg1='cats',arg2='dogs') # named arguments
'pi is {:.2f}'.format(3.14159) # returns 'pi is 3.14'
print 'first line\nsecond line' # normal strings allow for escaped characters print r'first line\nfirst line' # raw strings treat backslashes as literal characters
empty_dict = {} empty_dict = dict()
family = {'dad':'homer', 'mom':'marge', 'size':6} family = dict(dad='homer', mom='marge', size=6)
list_of_tuples = [('dad','homer'), ('mom','marge'), ('size', 6)] family = dict(list_of_tuples)
family['dad'] # returns 'homer' len(family) # returns 3 family.keys() # returns list: ['dad', 'mom', 'size'] family.values() # returns list: ['homer', 'marge', 6] family.items() # returns list of tuples: # [('dad', 'homer'), ('mom', 'marge'), ('size', 6)] 'mom' in family # returns True 'marge' in family # returns False (only checks keys)
family['cat'] = 'snowball' # add a new entry family['cat'] = 'snowball ii' # edit an existing entry del family['cat'] # delete an entry family['kids'] = ['bart', 'lisa'] # value can be a list family.pop('dad') # removes an entry and returns the value ('homer') family.update({'baby':'maggie', 'grandpa':'abe'}) # add multiple entries
family['mom'] # returns 'marge' family.get('mom') # same thing family['grandma'] # throws an error family.get('grandma') # returns None family.get('grandma', 'not found') # returns 'not found' (the default)
family['kids'][0] # returns 'bart' family['kids'].remove('lisa') # removes 'lisa'
'youngest child is %(baby)s' % family # returns 'youngest child is maggie'
empty_set = set()
languages = {'python', 'r', 'java'} # create a set directly snakes = set(['cobra', 'viper', 'python']) # create a set from a list
len(languages) # returns 3 'python' in languages # returns True
languages & snakes # returns intersection: {'python'} languages | snakes # returns union: {'cobra', 'r', 'java', 'viper', 'python'} languages - snakes # returns set difference: {'r', 'java'} snakes - languages # returns set difference: {'cobra', 'viper'}
languages.add('sql') # add a new element languages.add('r') # try to add an existing element (ignored, no error) languages.remove('java') # remove an element languages.remove('c') # try to remove a non-existing element (throws an error) languages.discard('c') # removes an element if present, but ignored otherwise languages.pop() # removes and returns an arbitrary element languages.clear() # removes all elements languages.update('go', 'spark') # add multiple elements (can also pass a list or set)
sorted(set([9, 0, 2, 1, 0])) # returns [0, 1, 2, 9]
def print_text(): print 'this is text'
print_text()
def print_this(x): print x
print_this(3) # prints 3 n = print_this(3) # prints 3, but doesn't assign 3 to n # because the function has no return statement
def square_this(x): return x**2
def square_this(x): """Return the square of a number.""" return x**2
square_this(3) # prints 9 var = square_this(3) # assigns 9 to var, but does not print 9
def calc(a, b, op='add'): if op == 'add': return a + b elif op == 'sub': return a - b else: print 'valid operations are add and sub'
calc(10, 4, op='add') # returns 14 calc(10, 4, 'add') # also returns 14: unnamed arguments are inferred by position calc(10, 4) # also returns 14: default for 'op' is 'add' calc(10, 4, 'sub') # returns 6 calc(10, 4, 'div') # prints 'valid operations are add and sub'
def stub(): pass
def min_max(nums): return min(nums), max(nums)
nums = [1, 2, 3] min_max_num = min_max(nums) # min_max_num = (1, 3)
min_num, max_num = min_max(nums) # min_num = 1, max_num = 3
def squared(x): return x**2
squared = lambda x: x**2
simpsons = ['homer', 'marge', 'bart'] def last_letter(word): return word[-1] sorted(simpsons, key=last_letter)
sorted(simpsons, key=lambda word: word[-1])
range(0, 3) # returns [0, 1, 2]: includes first value but excludes second value range(3) # same thing: starting at zero is the default range(0, 5, 2) # returns [0, 2, 4]: third argument specifies the 'stride'
fruits = ['apple', 'banana', 'cherry'] for i in range(len(fruits)): print fruits[i].upper()
for fruit in fruits: print fruit.upper()
for i in xrange(10**6): pass
family = {'dad':'homer', 'mom':'marge', 'size':6} for key, value in family.items(): print key, value
for index, fruit in enumerate(fruits): print index, fruit
for fruit in fruits: if fruit == 'banana': print "Found the banana!" break # exit the loop and skip the 'else' block else: # this block executes ONLY if the for loop completes without hitting 'break' print "Can't find the banana"
count = 0 while count < 5: print "This will print 5 times" count += 1 # equivalent to 'count = count + 1'
nums = [1, 2, 3, 4, 5] cubes = [] for num in nums: cubes.append(num**3)
cubes = [num**3 for num in nums] # [1, 8, 27, 64, 125]
cubes_of_even = [] for num in nums: if num % 2 == 0: cubes_of_even.append(num**3)
cubes_of_even = [num**3 for num in nums if num % 2 == 0] # [8, 64]
cubes_and_squares = [] for num in nums: if num % 2 == 0: cubes_and_squares.append(num3) else: cubes_and_squares.append(num2)
cubes_and_squares = [num3 if num % 2 == 0 else num2 for num in nums] # [1, 8, 9, 64, 25]
matrix = [[1, 2], [3, 4]] items = [] for row in matrix: for item in row: items.append(item)
items = [item for row in matrix for item in row] # [1, 2, 3, 4]
fruits = ['apple', 'banana', 'cherry'] unique_lengths = {len(fruit) for fruit in fruits} # {5, 6}
fruit_lengths = {fruit:len(fruit) for fruit in fruits} # {'apple': 5, 'banana': 6, 'cherry': 6} fruit_indices = {fruit:index for index, fruit in enumerate(fruits)} # {'apple': 0, 'banana': 1, 'cherry': 2}
simpsons = ['homer', 'marge', 'bart'] map(len, simpsons) # returns [5, 5, 4] map(lambda word: word[-1], simpsons) # returns ['r', 'e', 't']
[len(word) for word in simpsons] [word[-1] for word in simpsons]
reduce(lambda x, y: x + y, range(4)) # (((0+1)+2)+3) = 6
filter(lambda x: x % 2 == 0, range(5)) # returns [0, 2, 4]