Python Notes and Examples
← prev | next →     Top-level ToC     /data-structures.html     (printable version)

1 Lists

# 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)

2 Dicts

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

Given:

d = {'a': 1, 'b': 2, 'c': 3}
ks = d.keys()
vs = d.values()

Note that d.keys() and d.values() return views on the dict. If you change d, you’ll change ks and vs. If you want back something unchanging, do list(d.keys()).