Lists: Python snippets
Part of 30 Seconds of Python. Source: snippets/lists.py.
Every example below is run as a test.
chunk
Split a list into consecutive pieces of at most size items.
def chunk(items, size):
if size < 1:
raise ValueError("size must be >= 1")
return [items[i:i + size] for i in range(0, len(items), size)]
>>> chunk([1, 2, 3, 4, 5], 2)
[[1, 2], [3, 4], [5]]
flatten
Flatten one level of nesting.
def flatten(nested):
return [x for sub in nested for x in sub]
>>> flatten([[1, 2], [3], [], [4, 5]])
[1, 2, 3, 4, 5]
deep_flatten
Flatten lists and tuples nested to any depth (strings stay whole).
def deep_flatten(nested):
out = []
for x in nested:
if isinstance(x, (list, tuple)):
out.extend(deep_flatten(x))
else:
out.append(x)
return out
>>> deep_flatten([1, [2, [3, (4, 5)]], "ab"])
[1, 2, 3, 4, 5, 'ab']
unique
Remove duplicates while keeping the first-seen order.
def unique(items):
return list(dict.fromkeys(items))
>>> unique([3, 1, 3, 2, 1])
[3, 1, 2]
unique_by
Remove duplicates by a key function, keeping the first item per key.
def unique_by(items, key):
seen = set()
out = []
for x in items:
k = key(x)
if k not in seen:
seen.add(k)
out.append(x)
return out
>>> unique_by(["apple", "Avocado", "banana"], key=lambda s: s[0].lower())
['apple', 'banana']
duplicates
Return the values that appear more than once, in first-seen order.
def duplicates(items):
return [x for x, n in Counter(items).items() if n > 1]
>>> duplicates([1, 2, 2, 3, 3, 3, 4])
[2, 3]
compact
Drop falsy values (0, ‘’, None, False, empty containers).
def compact(items):
return [x for x in items if x]
>>> compact([0, 1, '', 'a', None, [], [2], False])
[1, 'a', [2]]
group_by
Group items into a dict of lists by a key function.
def group_by(items, key):
groups = {}
for x in items:
groups.setdefault(key(x), []).append(x)
return groups
>>> group_by(["one", "two", "three"], len)
{3: ['one', 'two'], 5: ['three']}
partition
Split into (matching, not_matching) in a single pass.
def partition(items, predicate):
yes, no = [], []
for x in items:
(yes if predicate(x) else no).append(x)
return yes, no
>>> partition(range(6), lambda n: n % 2 == 0)
([0, 2, 4], [1, 3, 5])
most_frequent
Return the most common value (the first one seen wins a tie).
def most_frequent(items):
return Counter(items).most_common(1)[0][0]
>>> most_frequent(['a', 'b', 'a', 'c', 'b', 'a'])
'a'
transpose
Swap rows and columns of a rectangular 2D list.
def transpose(rows):
return [list(col) for col in zip(*rows)]
>>> transpose([[1, 2, 3], [4, 5, 6]])
[[1, 4], [2, 5], [3, 6]]
zip_fill
Zip sequences of different lengths, padding the short ones.
def zip_fill(*seqs, fill=None):
return list(zip_longest(*seqs, fillvalue=fill))
>>> zip_fill([1, 2, 3], ['a'], fill='-')
[(1, 'a'), (2, '-'), (3, '-')]
rotate
Rotate a list n places to the left (negative n rotates right).
def rotate(items, n):
if not items:
return []
n %= len(items)
return items[n:] + items[:n]
>>> rotate([1, 2, 3, 4, 5], 2)
[3, 4, 5, 1, 2]
>>> rotate([1, 2, 3, 4, 5], -1)
[5, 1, 2, 3, 4]
sliding_window
Yield overlapping windows of size consecutive items.
def sliding_window(items, size):
it = iter(items)
window = tuple(islice(it, size))
if len(window) == size:
yield window
for x in it:
window = window[1:] + (x,)
yield window
>>> list(sliding_window([1, 2, 3, 4], 3))
[(1, 2, 3), (2, 3, 4)]
difference
Items of a not in b, keeping order and duplicates of a.
def difference(a, b):
exclude = set(b)
return [x for x in a if x not in exclude]
>>> difference([1, 2, 3, 2, 4], [2, 4])
[1, 3]
intersection
Items of a that are also in b, keeping the order of a.
def intersection(a, b):
keep = set(b)
return [x for x in a if x in keep]
>>> intersection([5, 1, 3, 1], [1, 5])
[5, 1, 1]
all_equal
True if every element is equal (also True for an empty list).
def all_equal(items):
return len(set(items)) <= 1 if all(_hashable(x) for x in items) else all(x == items[0] for x in items)
>>> all_equal([2, 2, 2]), all_equal([2, 3]), all_equal([])
(True, False, True)
index_all
Every index where value occurs.
def index_all(items, value):
return [i for i, x in enumerate(items) if x == value]
>>> index_all(['a', 'b', 'a', 'c', 'a'], 'a')
[0, 2, 4]
sort_by_keys
Sort dicts by several keys; prefix a key with ‘-‘ for descending.
def sort_by_keys(items, *keys):
result = list(items)
for key in reversed(keys): # stable sort: apply the least important key first
desc = key.startswith('-')
name = key.lstrip('-')
result.sort(key=lambda d: d[name], reverse=desc)
return result
>>> people = [{'n': 'b', 'age': 30}, {'n': 'a', 'age': 30}, {'n': 'c', 'age': 25}]
>>> [p['n'] for p in sort_by_keys(people, '-age', 'n')]
['a', 'b', 'c']
first
First item (optionally the first that matches predicate), else default.
def first(items, predicate=None, default=None):
return next((x for x in items if predicate is None or predicate(x)), default)
>>> first([1, 4, 6], lambda n: n > 3)
4
>>> first([], default='none')
'none'