-
Notifications
You must be signed in to change notification settings - Fork 69
Python Cheatsheet
- External Cheat Sheets
- 1. Types and Common Operators/Functions
- 2. Strings
- 3. Lists
- 4. Dictionaries
- 5. Conditionals
- 6. Functions
- 7. Loops
- 8. Files
Also check out our list of resources here
-
a in b: Test whetherais contained inband returns True if so.bcan be a string, list, tuple, set or dictionary. -
a not in b: Returns True irais NOT contained inb.bcan be a string, list, tuple, set or dictionary. -
type(obj): Returns the data type of anobj. -
str(obj): Returns a string representation of anobj, i.e.objcoerced to a string -
int(obj): Returns an integer representation of anobj, i.e.objcoerced to an integer -
float(obj): Returns a float representation of anobj, i.e.objcoerced to an float -
len(seq): Returns the number of items in a sequenceseq: a sequence can be a string, list, tuple, etc. -
range(int): Returns a sequences of integers from 0 toint-1. -
range(start, end, by): Returns a sequences of integers fromstarttoend-1, in steps ofby.
> range(4, 10, 2)
4, 6, 8-
string[index1 : index2]: Slices astringfromindex1toindex2(excluding index2) -
string.upper(): Makes astringall uppercase.
> s = "donut"
> s.upper()
DONUT-
string.lowercase(): Makes astringall lowercase. -
string.join(list): Concatenates each item inlistwith the delimiterstring.
> l = ["Billy", "Bob", "Thorton"]
> "".join(l)
"BillyBobThorton"
> "--".join(l)
"Billy--Bob--Thorton"-
string1.startswith(string2): ReturnsTrueifstring1starts withstring2,Falseotherwise. -
string1.endswith(string2): ReturnsTrueifstring1ends withstring2,Falseotherwise. -
substring in string: ReturnsTrueifsubstringis contained instring,Falseotherwise.
-
list[index]: Finds the item inlistwith the positionindex. -
list[index1 : index2]: Slices alistfromindex1toindex2(excluding index2) -
list.append(obj): Appendsobjto the end oflist -
list.extend(obj): Extendslistto includeobj, which is usually another list. -
list.index(obj): Returns index of first occurrence ofobjinlist; raisesValueErrorifobjnot inlist. -
list.remove(obj): Removes first instance ofobjinlist; raisesValueErrorifobjnot inlist. -
list.sort(): Sortslistin order, in place. -
list.count(obj): Returns an integer counting the number of occurrences ofobjinlist -
obj in list: ReturnsTrueifobtis contained inlist,Falseotherwise.
-
dict[key]: Returns the value paired withkeyindict.keyis 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: ReturnsTrueifdictcontainskey,Falseotherwise. -
dict.keys(): Returns a list ofdict's keys. -
dict.values(): Returns a list ofdict`'s values. -
dict.items(): Returns a list of key / value pairs indict`. Each list item is a 2 item tuple.
- 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- define function
> def function_name(arg1, arg2):
answer = arg1 + arg2
return(answer)- call function
> function_name(2, 3)
5- 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'- Read contents of file
example.txtinto variabletext
> 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)