-
Notifications
You must be signed in to change notification settings - Fork 71
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 whethera
is contained inb
and returns True if so.b
can be a string, list, tuple, set or dictionary. -
a not in b
: Returns True ira
is NOT contained inb
.b
can 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.obj
coerced to a string -
int(obj)
: Returns an integer representation of anobj
, i.e.obj
coerced to an integer -
float(obj)
: Returns a float representation of anobj
, i.e.obj
coerced 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 fromstart
toend
-1, in steps ofby
.
> range(4, 10, 2)
4, 6, 8
-
string[index1 : index2]
: Slices astring
fromindex1
toindex2
(excluding index2) -
string.upper()
: Makes astring
all uppercase.
> s = "donut"
> s.upper()
DONUT
-
string.lowercase()
: Makes astring
all lowercase. -
string.join(list)
: Concatenates each item inlist
with the delimiterstring
.
> l = ["Billy", "Bob", "Thorton"]
> "".join(l)
"BillyBobThorton"
> "--".join(l)
"Billy--Bob--Thorton"
-
string1.startswith(string2)
: ReturnsTrue
ifstring1
starts withstring2
,False
otherwise. -
string1.endswith(string2)
: ReturnsTrue
ifstring1
ends withstring2
,False
otherwise. -
substring in string
: ReturnsTrue
ifsubstring
is contained instring
,False
otherwise.
-
list[index]
: Finds the item inlist
with the positionindex
. -
list[index1 : index2]
: Slices alist
fromindex1
toindex2
(excluding index2) -
list.append(obj)
: Appendsobj
to the end oflist
-
list.extend(obj)
: Extendslist
to includeobj
, which is usually another list. -
list.index(obj)
: Returns index of first occurrence ofobj
inlist
; raisesValueError
ifobj
not inlist.
-
list.remove(obj)
: Removes first instance ofobj
inlist
; raisesValueError
ifobj
not inlist.
-
list.sort()
: Sortslist
in order, in place. -
list.count(obj)
: Returns an integer counting the number of occurrences ofobj
inlist
-
obj in list
: ReturnsTrue
ifobt
is contained inlist
,False
otherwise.
-
dict[key]
: Returns the value paired withkey
indict
.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
: ReturnsTrue
ifdict
containskey
,False
otherwise. -
dict.keys()
: Returns a list ofdict
'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.
- 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.txt
into 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)