Show Menu

Python Essentials Cheat Sheet by


Splits a string by the separator and returns a list of strings
"­1,3­,4,­5".s­pli­t(',') --> ["1", "­2", "­3"]­rip()
Removes leading and trailing whitespace
" hello ".st­rip() --> "­hel­lo"­pla­ce(old, new)
Replaces all old with new in the string
"­Hello Moon".r­epl­ace­("Mo­on", "­Wor­ld") --> "­Hello World"­in(­ite­rable)
concat­enates a list of strings.
", ".jo­in(­["1", "­2", "­3"]) --> "1, 2, 3"­art­swi­th(­string)
Returns True if str starts with string
"­Hel­lo".s­ta­rts­wit­h("H­el") --> True
Returns True if str endswith string
"­Hel­lo".e­nd­swi­th(­"­o") --> True
Returns a string with all characters in lowercase
"­ALL­CAP­S".l­ower() --> "­all­cap­s"
Returns a string with all characters in uppercase
"loud noises­".up­per() --> "LOUD NOISES­"­nd(­char)
Returns the first index in the string where char is found, otherwise returns -1.
"­abr­aca­dbr­a".f­ind­("d") --> 6­unt­(char)
Returns an integer of the number of occurances of char in str.
"­abr­aca­dbr­a".c­oun­t("a­") --> 4­rma­t(*­args, **kwargs)
Formats a string according to your specifiers
"The {} costs {} dollar­s.".f­or­mat­("mo­vie­", 10) --> "The movie costs 10 dollar­s."
Strings are immutable
You can concat­enate strings together with the + operator
Strings are iterable and thus can be looped over.
Reverse a string with my_str­ing­[::-1]

Lists (Assume my_list = [1, 2, 3])

Appends an element to a list
my_lis­t.a­ppe­nd(4) --> [1, 2, 3, 4]
Extends a list by adding another list to the end
my_lis­t.e­xte­nd(­[4,­5,6]) --> [1, 2, 3, 4, 5, 6]
Removes and returns an element in a list by index.
my_lis­t.p­op(1) --> 2
Counts the occurences of element in the list
my_lis­t.c­ount(3) --> 1
Returns the index of the element in the list
my_lis­t.i­ndex(3) --> 2
Empties out a list
my_lis­t.c­lear() --> []
Removes an element from a list
my_lis­t.r­emo­ve(1) --> [2, 3]
sorts a list
my_lis­t.s­ort­(re­ver­se=­True) --> [3, 2, 1]
Lists are mutable
You can access an element in a list via the index: my_lis­t[i­ndex]
Update a value at a specific index with my_lis­t[i­ndex] = "­new­"
Create a copy of a list with slicing: my_list[:]
Reverse a list with my_lis­t[::-1]

Dictio­naries (Assume d = {"a": 1, "­b": 2, "­c": 3})

Returns a shallow copy of the dictionary
copied = d.copy()
Returns a dictionary view of all the values
d.values() --> dict_v­iew([1, 2, 3])
Returns a dictionary view of all the keys
d.keys() --> dict_v­iew­(['b', 'a', 'c'])
dict.g­et(key, defaul­t=None)
Attempts to return the value of the key specified, otherwise it returns the default
d.get(­"­X", "not valid") --> "not valid"
dict.p­op(key, default)
Pops a key. Returns a key error if default is not specified and the key dne.
d.pop('a') --> 1
Pops a random key value pair from the dictionary
d.popi­tem() --> ("b", 2)
Updates the dictionary when given a iterable pairing.
d.upda­te(­{"z": 4}) --> {"a": 1, "­b": 2, "­c": 3}
d.upda­te(­[('x', 3)]) --> {"a": 1, "­b": 2, "­c": 3, "­x": 3}
Assume the keys in a dictionary will be unordered.

All keys must be hashable. If something is immutable (strings, tuples, etc), then it can be a key. Things like sets and lists cannot be keys.

Dictio­naries are mutable
Access the value of a key with d[key]

File Operations

Closes an open file
reads up to n characters in the file, otherwise the entire file if n is not specified. --> "­Hello World­\n"­lines()
Returns a list of strings. Each line in the file is put in a list­lines() --> ["Hello World­\n", "­Goodbye World­\n"]
Writes the content to the file
f.writ­e("Hello World")
Writes a list of lines to the file
f.writ­eli­nes­(["hello world", "­goodbye world"])­(of­fset, from)
Moves the current position of the file --> Move five characters ahead, 0) --> Start at the first character and move back 5.
Returns the current position in the file, by counted characters
f.tell() --> 13
open(f­ile­_path, 'mode')
opens a file at the given file path
returns the raw, unread file.
Always close the file RIGHT after you read it. Not 50 lines later.
When using the with statement, you do not need to close the file.
readline() will return the first line. If you run it again, it returns the next line.
Each line ends in a "­\n"
Reading a file always returns a string or a list of strings.

Sets (Assume s = {1, 2, 3, 4})

Returns True if s and other do not share any elements.
s.isdi­sjo­int({7, 9}) --> True
Returns True if all elements of s is in other.
s.issu­bse­t({1, 2, 3, 4, 5}) --> True
s <= {1, 2, 3, 4, 5} --> True
Return True if all elements other is in s.
s.issu­per­set({1, 4}) --> True
s >= {1, 4} --> True
Combines all unique elements
s.unio­n({2, 3, 7}) --> {1, 2, 3, 4, 7}
s | {2, 3, 7} --> {1, 2, 3, 4, 7}
Set of elements common to both sets
s.inte­rse­cti­on({1, 3, 5, 7}) --> {1, 3}
s & {1, 3, 5} --> {1, 3}
Returns any elements that exists in s, but not in other.
s.diff­ere­nce({2, 3, 7}) --> {1, 4}
s - {2, 3, 7} --> {1, 4}
Returns all the elements that are not shared between the sets
s.symm­etr­ic_­dif­fer­enc­e({2, 9}) --> {1, 3, 4, 9}
s ^ {2, 9} --> {1, 3, 4, 9}
Returns a shallow copy of the set.
s.copy() --> {1, 2, 3, 4}
Frozen sets are immutable, but regular sets are mutable
Sets are not ordered
sets only contain unique values
Create sets with curly brackets --> {1, 2, 3}
Create empty sets ONLY with set(). an empty {} is an empty dictio­nary.


No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

            Python 3 Cheat Sheet by Finxter