1. Imports¶
# 'generic import' of math moduleimportmathmath.sqrt(25)
5.0
# import a functionfrommathimportsqrtsqrt(25)# no longer have to reference the module
5.0
# import multiple functions at oncefrommathimportcos,floor
# import all functions in a module (generally discouraged)fromcsvimport*
# define an aliasimportdatetimeasdt
# show all functions in math moduleprint(dir(math))
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
2. Data Types¶
Determine the type of an object:
type(2)
int
type(2.0)
float
type('two')
str
type(True)
bool
type(None)
NoneType
Check if an object is of a given type:
isinstance(2.0,int)
False
isinstance(2.0,(int,float))
True
Convert an object to a given type:
float(2)
2.0
int(2.9)
2
str(2.9)
'2.9'
Zero,None, and empty containers are converted toFalse:
bool(0)
False
bool(None)
False
bool('')# empty string
False
bool([])# empty list
False
bool({})# empty dictionary
False
Non-empty containers and non-zeros are converted toTrue:
bool(2)
True
bool('two')
True
bool([2])
True
3. Math¶
10+4
14
10-4
6
10*4
40
10**4# exponent
10000
5%4# modulo - computes the remainder
1
# Python 2: returns 2 (because both types are 'int')# Python 3: returns 2.510/4
2
10/float(4)
2.5
# force '/' in Python 2 to perform 'true division' (unnecessary in Python 3)from__future__importdivision
10/4# true division
2.5
10//4# floor division
2
4. Comparisons and Boolean Operations¶
Assignment statement:
x=5
Comparisons:
x>3
True
x>=3
True
x!=3
True
x==5
True
Boolean operations:
5>3and6>3
True
5>3or5<3
True
notFalse
True
FalseornotFalseandTrue# evaluation order: not, and, or
True
5. Conditional Statements¶
# if statementifx>0:print('positive')
positive
# if/else statementifx>0:print('positive')else:print('zero or negative')
positive
# if/elif/else statementifx>0:print('positive')elifx==0:print('zero')else:print('negative')
positive
# single-line if statement (sometimes discouraged)ifx>0:print('positive')
positive
# single-line if/else statement (sometimes discouraged), known as a 'ternary operator''positive'ifx>0else'zero or negative'
'positive'
6. Lists¶
- List properties: ordered, iterable, mutable, can contain multiple data types
# create an empty list (two ways)empty_list=[]empty_list=list()
# create a listsimpsons=['homer','marge','bart']
Examine a list:
# print element 0simpsons[0]
'homer'
len(simpsons)
3
Modify a list (does not return the list):
# append element to endsimpsons.append('lisa')simpsons
['homer', 'marge', 'bart', 'lisa']
# append multiple elements to endsimpsons.extend(['itchy','scratchy'])simpsons
['homer', 'marge', 'bart', 'lisa', 'itchy', 'scratchy']
# insert element at index 0 (shifts everything right)simpsons.insert(0,'maggie')simpsons
['maggie', 'homer', 'marge', 'bart', 'lisa', 'itchy', 'scratchy']
# search for first instance and remove itsimpsons.remove('bart')simpsons
['maggie', 'homer', 'marge', 'lisa', 'itchy', 'scratchy']
# remove element 0 and return itsimpsons.pop(0)
'maggie'
# remove element 0 (does not return it)delsimpsons[0]simpsons
['marge', 'lisa', 'itchy', 'scratchy']
# replace element 0simpsons[0]='krusty'simpsons
['krusty', 'lisa', 'itchy', 'scratchy']
# concatenate lists (slower than 'extend' method)neighbors=simpsons+['ned','rod','todd']neighbors
['krusty', 'lisa', 'itchy', 'scratchy', 'ned', 'rod', 'todd']
Find elements in a list:
# counts the number of instancessimpsons.count('lisa')
1
# returns index of first instancesimpsons.index('itchy')
2
List slicing:
weekdays=['mon','tues','wed','thurs','fri']
# element 0weekdays[0]
'mon'
# elements 0 (inclusive) to 3 (exclusive)weekdays[0:3]
['mon', 'tues', 'wed']
# starting point is implied to be 0weekdays[:3]
['mon', 'tues', 'wed']
# elements 3 (inclusive) through the endweekdays[3:]
['thurs', 'fri']
# last elementweekdays[-1]
'fri'
# every 2nd element (step by 2)weekdays[::2]
['mon', 'wed', 'fri']
# backwards (step by -1)weekdays[::-1]
['fri', 'thurs', 'wed', 'tues', 'mon']
# alternative method for returning the list backwardslist(reversed(weekdays))
['fri', 'thurs', 'wed', 'tues', 'mon']
Sort a list in place (modifies but does not return the list):
simpsons.sort()simpsons
['itchy', 'krusty', 'lisa', 'scratchy']
# sort in reversesimpsons.sort(reverse=True)simpsons
['scratchy', 'lisa', 'krusty', 'itchy']
# sort by a keysimpsons.sort(key=len)simpsons
['lisa', 'itchy', 'krusty', 'scratchy']
Return a sorted list (does not modify the original list):
sorted(simpsons)
['itchy', 'krusty', 'lisa', 'scratchy']
sorted(simpsons,reverse=True)
['scratchy', 'lisa', 'krusty', 'itchy']
sorted(simpsons,key=len)
['lisa', 'itchy', 'krusty', 'scratchy']
Insert into an already sorted list, and keep it sorted:
num=[10,20,40,50]frombisectimportinsortinsort(num,30)num
[10, 20, 30, 40, 50]
Object references and copies:
# create a second reference to the same listsame_num=num
# modifies both 'num' and 'same_num'same_num[0]=0print(num)print(same_num)
[0, 20, 30, 40, 50][0, 20, 30, 40, 50]
# copy a list (two ways)new_num=num[:]new_num=list(num)
Examine objects:
numissame_num# checks whether they are the same object
True
numisnew_num
False
num==same_num# checks whether they have the same contents
True
num==new_num
True
7. Tuples¶
- Tuple properties: ordered, iterable, immutable, can contain multiple data types
- Like lists, but they don't change size
# create a tuple directlydigits=(0,1,'two')
# create a tuple from a listdigits=tuple([0,1,'two'])
# trailing comma is required to indicate it's a tuplezero=(0,)
Examine a tuple:
digits[2]
'two'
len(digits)
3
# counts the number of instances of that valuedigits.count(0)
1
# returns the index of the first instance of that valuedigits.index(1)
1
Modify a tuple:
# elements of a tuple cannot be modified (this would throw an error)# digits[2] = 2
# concatenate tuplesdigits=digits+(3,4)digits
(0, 1, 'two', 3, 4)
Other tuple operations:
# create a single tuple with elements repeated (also works with lists)(3,4)*2
(3, 4, 3, 4)
# sort a list of tuplestens=[(20,60),(10,40),(20,30)]sorted(tens)# sorts by first element in tuple, then second element
[(10, 40), (20, 30), (20, 60)]
# tuple unpackingbart=('male',10,'simpson')# create a tuple(sex,age,surname)=bart# assign three values at onceprint(sex)print(age)print(surname)
male10simpson
8. Strings¶
- String properties: iterable, immutable
# convert another data type into a strings=str(42)s
'42'
# create a string directlys='I like you'
Examine a string:
s[0]
'I'
len(s)
10
String slicing is like list slicing:
s[:6]
'I like'
s[7:]
'you'
s[-1]
'u'
Basic string methods (does not modify the original string):
s.lower()
'i like you'
s.upper()
'I LIKE YOU'
s.startswith('I')
True
s.endswith('you')
True
# checks whether every character in the string is a digits.isdigit()
False
# returns index of first occurrence, but doesn't support regexs.find('like')
2
# returns -1 since not founds.find('hate')
-1
# replaces all instances of 'like' with 'love's.replace('like','love')
'I love you'
Split a string:
# split a string into a list of substrings separated by a delimiters.split(' ')
['I', 'like', 'you']
# equivalent (since space is the default delimiter)s.split()
['I', 'like', 'you']
s2='a, an, the's2.split(',')
['a', ' an', ' the']
Join or concatenate strings:
# join a list of strings into one string using a delimiterstooges=['larry','curly','moe']' '.join(stooges)
'larry curly moe'
# concatenate stringss3='The meaning of life is's4='42's3+' '+s4
'The meaning of life is 42'
Remove whitespace from the start and end of a string:
s5=' ham and cheese 's5.strip()
'ham and cheese'
String substitutions:
# old way'raining%s and%s'%('cats','dogs')
'raining cats and dogs'
# new way'raining{} and{}'.format('cats','dogs')
'raining cats and dogs'
# new way (using named arguments)'raining{arg1} and{arg2}'.format(arg1='cats',arg2='dogs')
'raining cats and dogs'
String formatting (more examples):
# use 2 decimal places'pi is{:.2f}'.format(3.14159)
'pi is 3.14'
Normal strings versus raw strings:
# normal strings allow for escaped charactersprint('first line\nsecond line')
first linesecond line
# raw strings treat backslashes as literal charactersprint(r'first line\nfirst line')
first line\nfirst line
9. Dictionaries¶
- Dictionary properties: unordered, iterable, mutable, can contain multiple data types
- Made of key-value pairs
- Keys must be unique, and can be strings, numbers, or tuples
- Values can be any type
# create an empty dictionary (two ways)empty_dict={}empty_dict=dict()
# create a dictionary (two ways)family={'dad':'homer','mom':'marge','size':6}family=dict(dad='homer',mom='marge',size=6)family
{'dad': 'homer', 'mom': 'marge', 'size': 6}# convert a list of tuples into a dictionarylist_of_tuples=[('dad','homer'),('mom','marge'),('size',6)]family=dict(list_of_tuples)family
{'dad': 'homer', 'mom': 'marge', 'size': 6}Examine a dictionary:
# pass a key to return its valuefamily['dad']
'homer'
# return the number of key-value pairslen(family)
3
# check if key exists in dictionary'mom'infamily
True
# dictionary values are not checked'marge'infamily
False
# returns a list of keys (Python 2) or an iterable view (Python 3)family.keys()
['dad', 'mom', 'size']
# returns a list of values (Python 2) or an iterable view (Python 3)family.values()
['homer', 'marge', 6]
# returns a list of key-value pairs (Python 2) or an iterable view (Python 3)family.items()
[('dad', 'homer'), ('mom', 'marge'), ('size', 6)]Modify a dictionary (does not return the dictionary):
# add a new entryfamily['cat']='snowball'family
{'cat': 'snowball', 'dad': 'homer', 'mom': 'marge', 'size': 6}# edit an existing entryfamily['cat']='snowball ii'family
{'cat': 'snowball ii', 'dad': 'homer', 'mom': 'marge', 'size': 6}# delete an entrydelfamily['cat']family
{'dad': 'homer', 'mom': 'marge', 'size': 6}# dictionary value can be a listfamily['kids']=['bart','lisa']family
{'dad': 'homer', 'kids': ['bart', 'lisa'], 'mom': 'marge', 'size': 6}# remove an entry and return the valuefamily.pop('dad')
'homer'
# add multiple entriesfamily.update({'baby':'maggie','grandpa':'abe'})family
{'baby': 'maggie', 'grandpa': 'abe', 'kids': ['bart', 'lisa'], 'mom': 'marge', 'size': 6}Access values more safely withget:
family['mom']
'marge'
# equivalent to a dictionary lookupfamily.get('mom')
'marge'
# this would throw an error since the key does not exist# family['grandma']
# return None if not foundfamily.get('grandma')
# provide a default return value if not foundfamily.get('grandma','not found')
'not found'
Access a list element within a dictionary:
family['kids'][0]
'bart'
family['kids'].remove('lisa')family
{'baby': 'maggie', 'grandpa': 'abe', 'kids': ['bart'], 'mom': 'marge', 'size': 6}String substitution using a dictionary:
'youngest child is%(baby)s'%family
'youngest child is maggie'
10. Sets¶
- Set properties: unordered, iterable, mutable, can contain multiple data types
- Made of unique elements (strings, numbers, or tuples)
- Like dictionaries, but with keys only (no values)
# create an empty setempty_set=set()
# create a set directlylanguages={'python','r','java'}
# create a set from a listsnakes=set(['cobra','viper','python'])
Examine a set:
len(languages)
3
'python'inlanguages
True
Set operations:
# intersectionlanguages&snakes
{'python'}# unionlanguages|snakes
{'cobra', 'java', 'python', 'r', 'viper'}# set differencelanguages-snakes
{'java', 'r'}# set differencesnakes-languages
{'cobra', 'viper'}Modify a set (does not return the set):
# add a new elementlanguages.add('sql')languages
{'java', 'python', 'r', 'sql'}# try to add an existing element (ignored, no error)languages.add('r')languages
{'java', 'python', 'r', 'sql'}# remove an elementlanguages.remove('java')languages
{'python', 'r', 'sql'}# try to remove a non-existing element (this would throw an error)# languages.remove('c')
# remove an element if present, but ignored otherwiselanguages.discard('c')languages
{'python', 'r', 'sql'}# remove and return an arbitrary elementlanguages.pop()
'python'
# remove all elementslanguages.clear()languages
set()
# add multiple elements (can also pass a set)languages.update(['go','spark'])languages
{'go', 'spark'}Get a sorted list of unique elements from a list:
sorted(set([9,0,2,1,0]))
[0, 1, 2, 9]
11. Defining Functions¶
Define a function with no arguments and no return values:
defprint_text():print('this is text')
# call the functionprint_text()
this is text
Define a function with one argument and no return values:
defprint_this(x):print(x)
# call the functionprint_this(3)
3
# prints 3, but doesn't assign 3 to n because the function has no return statementn=print_this(3)
3
Define a function with one argument and one return value:
defsquare_this(x):returnx**2
# include an optional docstring to describe the effect of a functiondefsquare_this(x):"""Return the square of a number."""returnx**2
# call the functionsquare_this(3)
9
# assigns 9 to var, but does not print 9var=square_this(3)
Define a function with two 'positional arguments' (no default values) and one 'keyword argument' (has a default value):
defcalc(a,b,op='add'):ifop=='add':returna+belifop=='sub':returna-belse:print('valid operations are add and sub')
# call the functioncalc(10,4,op='add')
14
# unnamed arguments are inferred by positioncalc(10,4,'add')
14
# default for 'op' is 'add'calc(10,4)
14
calc(10,4,'sub')
6
calc(10,4,'div')
valid operations are add and sub
Usepass as a placeholder if you haven't written the function body:
defstub():pass
Return two values from a single function:
defmin_max(nums):returnmin(nums),max(nums)
# return values can be assigned to a single variable as a tuplenums=[1,2,3]min_max_num=min_max(nums)min_max_num
(1, 3)
# return values can be assigned into multiple variables using tuple unpackingmin_num,max_num=min_max(nums)print(min_num)print(max_num)
13
12. Anonymous (Lambda) Functions¶
- Primarily used to temporarily define a function for use by another function
# define a function the "usual" waydefsquared(x):returnx**2
# define an identical function using lambdasquared=lambdax:x**2
Sort a list of strings by the last letter:
# without using lambdasimpsons=['homer','marge','bart']deflast_letter(word):returnword[-1]sorted(simpsons,key=last_letter)
['marge', 'homer', 'bart']
# using lambdasorted(simpsons,key=lambdaword:word[-1])
['marge', 'homer', 'bart']
13. For Loops and While Loops¶
range returns a list of integers (Python 2) or a sequence (Python 3):
# includes the start value but excludes the stop valuerange(0,3)
[0, 1, 2]
# default start value is 0range(3)
[0, 1, 2]
# third argument is the step valuerange(0,5,2)
[0, 2, 4]
# Python 2 only: use xrange to create a sequence rather than a list (saves memory)xrange(100,100000,5)
xrange(100, 100000, 5)
for loops:
# not the recommended stylefruits=['apple','banana','cherry']foriinrange(len(fruits)):print(fruits[i].upper())
APPLEBANANACHERRY
# recommended styleforfruitinfruits:print(fruit.upper())
APPLEBANANACHERRY
# iterate through two things at once (using tuple unpacking)family={'dad':'homer','mom':'marge','size':6}forkey,valueinfamily.items():print(key,value)
('dad', 'homer')('mom', 'marge')('size', 6)# use enumerate if you need to access the index value within the loopforindex,fruitinenumerate(fruits):print(index,fruit)
(0, 'apple')(1, 'banana')(2, 'cherry')
for/else loop:
forfruitinfruits:iffruit=='banana':print('Found the banana!')break# exit the loop and skip the 'else' blockelse:# this block executes ONLY if the for loop completes without hitting 'break'print("Can't find the banana")
Found the banana!
while loop:
count=0whilecount<5:print('This will print 5 times')count+=1# equivalent to 'count = count + 1'
This will print 5 timesThis will print 5 timesThis will print 5 timesThis will print 5 timesThis will print 5 times
14. Comprehensions¶
List comprehension:
# for loop to create a list of cubesnums=[1,2,3,4,5]cubes=[]fornuminnums:cubes.append(num**3)cubes
[1, 8, 27, 64, 125]
# equivalent list comprehensioncubes=[num**3fornuminnums]cubes
[1, 8, 27, 64, 125]
# for loop to create a list of cubes of even numberscubes_of_even=[]fornuminnums:ifnum%2==0:cubes_of_even.append(num**3)cubes_of_even
[8, 64]
# equivalent list comprehension# syntax: [expression for variable in iterable if condition]cubes_of_even=[num**3fornuminnumsifnum%2==0]cubes_of_even
[8, 64]
# for loop to cube even numbers and square odd numberscubes_and_squares=[]fornuminnums:ifnum%2==0:cubes_and_squares.append(num**3)else:cubes_and_squares.append(num**2)cubes_and_squares
[1, 8, 9, 64, 25]
# equivalent list comprehension (using a ternary expression)# syntax: [true_condition if condition else false_condition for variable in iterable]cubes_and_squares=[num**3ifnum%2==0elsenum**2fornuminnums]cubes_and_squares
[1, 8, 9, 64, 25]
# for loop to flatten a 2d-matrixmatrix=[[1,2],[3,4]]items=[]forrowinmatrix:foriteminrow:items.append(item)items
[1, 2, 3, 4]
# equivalent list comprehensionitems=[itemforrowinmatrixforiteminrow]items
[1, 2, 3, 4]
Set comprehension:
fruits=['apple','banana','cherry']unique_lengths={len(fruit)forfruitinfruits}unique_lengths
{5, 6}Dictionary comprehension:
fruit_lengths={fruit:len(fruit)forfruitinfruits}fruit_lengths
{'apple': 5, 'banana': 6, 'cherry': 6}fruit_indices={fruit:indexforindex,fruitinenumerate(fruits)}fruit_indices
{'apple': 0, 'banana': 1, 'cherry': 2}15. Map and Filter¶
map applies a function to every element of a sequence and returns a list (Python 2) or iterator (Python 3):
simpsons=['homer','marge','bart']map(len,simpsons)
[5, 5, 4]
# equivalent list comprehension[len(word)forwordinsimpsons]
[5, 5, 4]
map(lambdaword:word[-1],simpsons)
['r', 'e', 't']
# equivalent list comprehension[word[-1]forwordinsimpsons]
['r', 'e', 't']
filter returns a list (Python 2) or iterator (Python 3) containing the elements from a sequence for which a condition isTrue:
nums=range(5)filter(lambdax:x%2==0,nums)
[0, 2, 4]
# equivalent list comprehension[numfornuminnumsifnum%2==0]
[0, 2, 4]