Python Notes and Examples

Data Structures

Lists

li = ['a', 'b', 'c', 'd']
li.index('c') #=> 2
li.append('e')
li.pop() #=> 'e'
len(li)  #=> 4
li[1:3]  #=> ['b', 'c']
del li[1]
# ['a', 'c', 'd']  others shift over
li[1:1] = 'b'
# ['a', 'b', 'c', 'd']

for e in li:
    print(e)

for idx, e in enumerate(li):
    print(idx, '-->', e)

[f'={s}=' for s in li]
#=> ['=a=', '=b=', '=c=', '=d=']

# Partition a list into n-sized chunks.
def partition(coll, n):
    return [ coll[i:i+n] for i in range(0, len(coll), n) ]

Note that slicing gives you a shallow copy.

To loop over items from multiple lists, grouped together:

a = [1, 2, 3]
b = ['x', 'y', 'z']
c = [11, 12, 13]
for i, j, k in zip(a, b, c):
    print(i,j,k)

Invert a Matrix

list(zip(*m))

Dicts

d = {'a': 1, 'b': 2}
d['c'] = 3

d['z'] = 4
del d['z']

# dict comprehension
d2 = {k: some_fn(k) for k in some_list}

for k,v in d.items():
    print(k, '-->', v)

# These all give you back views on the dict; if you
# change `d`, ks/vs/itms change too.
ks   = d.keys()
vs   = d.values()
itms = d.items()

list(d)  #=> ['a', 'c', 'b'] that is, just the keys

dict.fromkeys(['a', 'b', 'c'])        #=> `{'a': None, 'c': None, 'b': None}`
dict.fromkeys(['a', 'b', 'c'], True)  #=> `{'a': True, 'c': True, 'b': True}`

Sets

s = {'a', 'b', 'c'}
s.add('d')
s.discard('d') # ok if 'd' not in s
s.remove('d')  # exception if 'd' not in s
s.pop()

# set comprehension
s = {some_func(x) for x in s}

s1.difference(s2)           # s1 minus elems in s2
s1.intersection(s2)         # elems in both s1 and s2
s1.symmetric_difference(s2) # elems in s1 *or* s2, but not in both
s1.union(s2)

Note:

non-mutating (and op) mutating
difference (-) difference_update
intersection (&) intersection_update
symmetric_difference (^) symmetric_difference_update
union (|) update

Comprehensions Recap

Data Structures Recap

Type Check for Item Remove Item Add Item
list 'a' in li
li.index('a')
del li[2]
li.pop()
li.remove('a')
li.append('x')
li.extend(['y', 'z'])
li.insert(idx, 'x')
dict 'a' in d del d['a']
d.pop('a')
d.popitem()
d['x'] = 7
d.update()
set 'a' in s s.remove('a')
s.discard('a')
s.pop()
s.add('x')
s.update()