Data Structures
Lists
= ['a', 'b', 'c', 'd']
li 'c') # => 2
li.index('e')
li.append(# => 'e'
li.pop() len(li) # => 4
1:3] # => ['b', 'c']
li[del li[1]
# ['a', 'c', 'd'] others shift over
1:1] = 'b'
li[# ['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.
Zip a bunch of lists together:
>>> list(zip([1, 2, 3], ['a', 'b', 'c'], [11, 22, 33]))
1, 'a', 11), (2, 'b', 22), (3, 'c', 33)] [(
Transpose a Matrix
That is, flip rows with cols:
>>> a = [[1, 2], [3, 4], [5, 6]]
>>> for i in a:
print(i)
...
...1, 2]
[3, 4]
[5, 6]
[>>> for i in list(zip(*a)):
print(i)
...
...1, 3, 5)
(2, 4, 6) (
Note though, you get back a list of tuples rather than lists.
Dicts
= {'a': 1, 'b': 2}
d 'c'] = 3
d[
'z'] = 4
d[del d['z']
# dict comprehension
= {k: some_fn(k) for k in some_list}
d2
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.
= d.keys()
ks = d.values()
vs = d.items()
itms
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
= {'a', 'b', 'c'}
s 'd')
s.add('d') # ok if 'd' not in s
s.discard('d') # exception if 'd' not in s
s.remove(
s.pop()
# set comprehension
= {some_func(x) for x in s}
s
# s1 minus elems in s2
s1.difference(s2) # elems in both s1 and s2
s1.intersection(s2) # elems in s1 *or* s2, but not in both
s1.symmetric_difference(s2) s1.union(s2)
Note:
non-mutating (and op) | mutating |
---|---|
difference (- ) |
difference_update |
intersection (& ) |
intersection_update |
symmetric_difference (^ ) |
symmetric_difference_update |
union (| ) |
update |
Comprehensions Recap
- List comprehension:
[x**2 for x in range(10)]
- Dict comprehension:
{f'={i}=': i**2 for i in range(10)}
- Set comprehension:
{x for x in 'aabaabbbaababa'}
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() |