Python
Arrays
Creating
python
a = []
a = [1,2,3]
a = list(range(1,11)) # 1 ... 10
a = [x for x in [3, 4, 5, 6, 7] if x > 5]
a = [0] * 3 # [0,0,0]
Accessing
python
a = [1,2,3]
print(a[0]) # 1
print(a[-1]) # 3
Manipulating
Adding
python
a = []
a.append(1)
a.extend([9, 11, 13])
a += [6,7,8]
a.insert(0, 2) # Insert 2 at index 0
Removing
python
li = ['bread', 'butter', 'eggs', 'milk']
li.pop() # returns and removes 'milk'
li.pop(2) # returns and removes 'eggs'
del li[0] # removes 'bread'
li.remove('butter')
Slicing
python
# a_list[start:end]
# a_list[start:end:step]
a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
a[2:5] # ['bacon', 'tomato', 'ham']
a[-3:] # ['tomato', 'ham', 'lobster']
a[-5:-2] # ['egg', 'bacon', 'tomato']
a[:4] # ['spam', 'egg', 'bacon', 'tomato']
a[2:] # ['bacon', 'tomato', 'ham', 'lobster']
a[0:6:2] # ['spam', 'bacon', 'ham']
a[6:0:-2] # ['lobster', 'tomato', 'egg']
a[::-1] # ['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']
a[:] # Create a copy of an array
Sorting
python
li = [3, 1, 3, 2, 5]
li.sort() # [1, 2, 3, 3, 5]
li.reverse() # [5, 3, 3, 2, 1]
sorted(li) # returns a sorted copy of li
li = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10)
]
sorted(li, key=lambda x: x[2])
sorted(li, cmp=lambda x,y: 1 if x<y else -1) # Negative return means second number is "less than"
Filtering
python
a = list(filter(lambda x : x % 2 == 1, range(1, 20)))
Strings
Strings act a lot like arrays/lists in Python, so many of the methods still apply.
Helper Functions
python
s = 'spam'
s in 'I saw spamalot!' # True
s not in 'I saw The Holy Grail!' # True
s = '12345' * 5 # '1234512345123451234512345'
"#".join(["John", "Peter", "Vicky"]) # 'John#Peter#Vicky'
"Hello, world!".endswith("!") # True
"Hello, world!".startswith("H") # True
Dictionaries
Creating
python
d = {}
d = {'color': 'green', 'points', 5}
Accessing
python
d['color']
d.get('points') # Returns None or value of points
d.get('points', 0) # Default value
d['age'] = 30
Removing
python
del d['age']
Iterating
python
for key, value in d.items():
# do something
for key in d.keys():
# do something
for value in d.values():
# do something
Zipping
python
group_1 = ['kai', 'abe', 'ada', 'gus', 'zoe']
group_2 = ['jen', 'eva', 'dan', 'isa', 'meg']
pairings = {name:name_2 for name, name_2 in zip(group_1, group_2)}
# {'kai': 'jen', 'abe': 'eva', 'ada': 'dan', 'gus': 'isa', 'zoe': 'meg'}
Sorting
By Key
python
my_dict = {'b': 2, 'a': 1, 'c': 3}
sorted_dict_by_keys = sorted(my_dict.items())
# [('a', 1), ('b', 2), ('c', 3)]
By Value
dict.items()
returns a tuple of the key value pairs for each iteration, so we can use sorted and use the value of the pair to return a list of the sorted pairs.
python
my_dict = {'b': 2, 'a': 1, 'c': 3}
sorted_dict_by_values = sorted(my_dict.items(), key=lambda item: item[1])
# [('a', 1), ('b', 2), ('c', 3)]
OrderedDict
OrderedDicts preserve the order in which the items were added, whereas normal dicts do not guarantee the order upon iteration. So you can sort the dictionary by key or value, and then pass that into OrderedDict to have a dict-like structure that preserves the inserted order.
python
from collections import OrderedDict
my_dict = {'b': 2, 'a': 4, 'c': 3}
sorted_dict_by_keys = OrderedDict(sorted(my_dict.items()))
for key, value in sorted_dict_by_keys:
# do something
Heap
heapq
is a module that implements a heap structure on a list of items. It's helpful for finding kth largest/smallest elements and priority queues.
python
import heapq
li = [10, 20, 15, 30, 40]
heapq.heapify(li)
# [10, 20, 15, 30, 40]
# Appending an element
heapq.heappush(h, 5)
# Pop the smallest element from the heap
min = heapq.heappop(h)
# Push a new element (5), then pop the smallest element and return
min = heapq.heappushpop(h, 5)
# Pop the smallest element, and then push new element (5)
min = heapq.heapreplace(h, 5)
# Find the 3 largest elements
maxi = heapq.nlargest(3, h)
# [40, 30, 20]
# Find the 3 smallest elements
min = heapq.nsmallest(3, h)
# [10, 15, 20]
# Merge heaps
h3 = list(heapq.merge(h1, h2))