Cheatography
https://cheatography.com
Some common data structures and their methods
This is a draft cheat sheet. It is a work in progress and is not finished yet.
Lists (and strings)
Concatenation |
my_list = list_1 + list_2
|
Append to the end |
my_list.append(new_element)
|
Check if in list |
|
Find in list |
position = my_list.index(element)
|
Remove last element |
|
Insert element at position |
my_list.insert(position, element)
|
Remove from list (by position) |
my_list.pop(position)
|
Remove from list (by element) |
my_list.remove(element)
|
Sort |
|
Reverse order |
|
Count elements |
number = my_list.count(element)
|
The same operations apply to strings, understood as lists of characters.
Sets
Add element |
|
Remove random element |
|
Remove specific element |
my_set.remove(element)
|
Add elements from other iterable |
my_set.update(iterable)
|
Union, intersection, difference |
new_set = my_set.union(other_set) new_set = my_set.intersection(other_set) new_set = my_set.difference(other_set)}
|
Dictionaries
List of keys or values |
keys = my_dict.keys() values = my_dict.values()
|
List of tuples (key, value) |
items = my_dict.items()
|
Update dictionary (or join two) |
my_dict.update({key: value}) my_dict.update(other_dict)
|
Remove item by key |
|
Remove last added item |
|
Copy dictionary |
new_dict = my_dict.copy()
|
|
|
List/string slicing
First/last n elements |
my_list[:n]
, my_list[n:]
|
From element n to element m, with step s |
|
Comprehensions
List comprehension |
lc = [n ** 2 for n in range(10) if n % 2 == 0]
|
Set comprehension |
sc = {n ** 2 for n in range(10) if n % 2 == 0}
|
Dictionary comprehension |
dc = {n: n ** 2 for n in range(10) if n % 2 == 0}
|
Generator comprehension |
gc = (n ** 2 for n in range(10) if n % 2 == 0)
|
Tuples
Count elements |
number = my_tuple.count(element)
|
Element in tuple |
|
Find in tuple |
position = my_tuple.index(element)
|
Advanced iterables
Import relevant modules |
|
Dictionary with default values |
def_dict = collections.defaultdict()
|
Dictionary remembering the order of items |
ord_dict = collections.OrderedDict()
|
Itertools module
Import relevant modules |
|
Cycle infinitely through iterable elements |
itertools.cycle(iterable)
|
Loop through the cumulative sum of the iterable |
itertools.accumulate([1,1,3,4])
|
Loop through pairwise contiguous elements |
itertools.accumulate(iterable)
|
Cartesian product of iterables |
itertools.product(iter_a, iter_b)
|
All permutations of an iterable |
itertools.permutations(iterable)
|
Length-r combinations from an iterable |
itertools.combinations(iterable)
|
In the accumulate()
function's argument, the iterable must contain elements which can be summed together. In other words, it can't have strings and integers at the same time as they can't be summed.
|