Skip to content

Latest commit

 

History

History
323 lines (279 loc) · 67.2 KB

File metadata and controls

323 lines (279 loc) · 67.2 KB

list – methods & common operations

Method/Operation What it does Example Special errors / corner cases
list(iterable) Create a new list from an iterable (or empty if no arg). list("ab") → ['a', 'b'] TypeError if argument is not iterable or if more than one positional arg is passed.
[...] literal Create a list with given elements. [1, 2, 3] Expression errors only (e.g. invalid syntax); list itself is fine.
List comprehension Build a list from a loop/condition. [x*x for x in range(3)] → [0, 1, 4] Any error inside the expression or loop (e.g. ZeroDivisionError) will propagate.
lst.append(x) Add single element at end, in place. lst = [1]; lst.append(2) → [1, 2] Returns None; TypeError only for wrong arg count.
lst.extend(iterable) Append all elements from iterable. lst.extend([3, 4]) TypeError if iterable is not iterable (e.g. lst.extend(5)).
lst.insert(i, x) Insert x at index i (before current element at i). lst.insert(1, 99) If i < 0, inserts near start; if i > len, inserts at end. TypeError if i not int-like.
lst.remove(x) Remove first occurrence of x. [1, 2, 2].remove(2) → [1, 2] ValueError: list.remove(x): x not in list if not present.
lst.pop([i]) Remove and return element at i (default last). lst.pop(), lst.pop(0) IndexError: pop from empty list if list empty; IndexError if index out of range; TypeError if i not int-like.
lst.clear() Remove all elements (empty the list). lst.clear() → [] Returns None; TypeError if any arg is passed.
lst.index(x[, start[, end]]) Return first index of x in [start:end). [1, 2, 3, 2].index(2, 2) → 3 ValueError: x is not in list if not found in that range; TypeError if start/end not int-like.
lst.count(x) Count occurrences of x. [1, 2, 2].count(2) → 2 No error if x absent (returns 0).
lst.sort(key=None, reverse=False) Sort list in place. lst.sort(), lst.sort(key=len, reverse=True) TypeError if elements can’t be compared (e.g. [1, "a"]); any error in key function propagates. Returns None.
lst.reverse() Reverse list in place. lst.reverse() Returns None; TypeError if called with arguments.
lst.copy() Shallow copy of list. lst2 = lst.copy() Only top-level list is new; nested objects are shared (mutating nested items affects both).
lst[i] Element at index i. [10, 20][1] → 20 IndexError: list index out of range if i invalid; TypeError if i not int/slice.
lst[start:stop:step] Slicing returns new list. [0,1,2,3][1:3] → [1,2] Out-of-range indices are silently clipped; step=0ValueError.
lst1 + lst2 Concatenate two lists. [1] + [2,3] → [1,2,3] TypeError if second operand not a list (e.g. [1]+(2,)).
lst * n Repeat list n times. [1,2] * 3 → [1,2,1,2,1,2] TypeError if n not int; negative or zero → empty or no elements.
x in lst / x not in lst Membership test (linear search). 2 in [1,2,3] → True Uses == for comparison; any error in __eq__ of elements propagates.
for x in lst: Iterate over elements in order. for x in lst: ... Safe; iteration over a list modified during loop can give surprising results but no direct error.
len(lst) Number of elements. len([1,2,3]) → 3 No special error for lists.
lst1 == lst2, lst1 < lst2 Compare lists lexicographically. [1,2] < [1,3] → True Comparisons with other non-sequence types → False for ==/!=, but <, > etc may give TypeError if elements incomparable (e.g. ["a"] < [1]).

tuple – methods & common operations

Method/Operation What it does Example Special errors / corner cases
tuple(iterable) Create tuple from iterable (or empty if no arg). tuple([1,2]) → (1, 2) TypeError if argument not iterable or too many positional args.
( ... ) literal Create a tuple. (1, 2, 3) Single-element tuple must use comma: (1,). Without comma, it’s just 1.
Tuple “packing” Assign multiple values into a tuple automatically. t = 1, 2, 3 # (1,2,3) Just syntax sugar; no special error.
Tuple “unpacking” Assign tuple elements to multiple variables. a, b = (1, 2) ValueError if counts don’t match (too many/few values to unpack).
t.count(x) Count occurrences of x. (1, 2, 2).count(2) → 2 Returns 0 if not found; TypeError only for bad arg count.
t.index(x[, start[, end]]) First index of x (within slice). (1,2,3,2).index(2,2) → 3 ValueError: tuple.index(x): x not in tuple if missing; TypeError if start/end not int-like.
t[i] Element at index i. (10, 20)[1] → 20 IndexError if out of range; TypeError if i not int/slice.
t[start:stop:step] Slice returns new tuple. (0,1,2,3)[1:3] → (1,2) Same slicing rules as lists (step=0ValueError).
t1 + t2 Concatenate tuples. (1,) + (2,3) → (1,2,3) TypeError if second operand not tuple.
t * n Repeat tuple. (1,2) * 3 → (1,2,1,2,1,2) TypeError if n not int.
x in t / x not in t Membership test (linear). 2 in (1,2,3) → True Same caveats as list membership regarding ==.
for x in t: Iterate over elements. for x in t: ... Tuples can’t be modified, so structure is safe while iterating.
len(t) Number of elements. len((1,2,3)) → 3
t1 == t2, t1 < t2 Lexicographic comparison. (1,2) < (1,3) → True Comparisons across incompatible element types can raise TypeError.
Immutability operations You cannot assign or delete items. t[0] = 10 TypeError: 'tuple' object does not support item assignment; same for del t[0].

String – methods & common operations

Core transformation & formatting

Method What it does Example Special errors / corner cases
s.capitalize() First char uppercase, rest lowercase. "hello world".capitalize()'Hello world'
s.casefold() Lowercase aggressively (for comparisons). "ß".casefold()'ss'
s.center(width, fillchar=' ') Pad both sides to given width. "hi".center(6, "-")'--hi--' TypeError if width not int / fillchar not 1-char str.
s.encode(encoding='utf-8', errors='strict') Encode to bytes. "hi".encode("utf-8")b'hi' LookupError if encoding unknown; UnicodeEncodeError if chars can’t be encoded and errors='strict'.
s.expandtabs(tabsize=8) Replace \t with spaces. "a\tb".expandtabs(4)'a b' TypeError if tabsize not int.
s.format(*args, **kwargs) Advanced formatting with {} placeholders. "Hi {}".format("Bob")'Hi Bob' IndexError (positional index out of range), KeyError (missing named key), ValueError (bad format spec), TypeError (wrong arg types).
s.format_map(mapping) Like format, but uses mapping directly. "{x} {y}".format_map({"x": 1, "y": 2})'1 2' KeyError if key missing; ValueError / TypeError similar to format.
s.lower() Return lowercase copy. "Hi".lower()'hi'
s.swapcase() Swap case of each letter. "Hi".swapcase()'hI'
s.title() Title-case (Each Word Like This). "hello world".title()'Hello World'
s.upper() Return uppercase copy. "hi".upper()'HI'
s.zfill(width) Pad on the left with zeros. "42".zfill(5)'00042' TypeError if width not int.

Stripping and padding

Let t = " hi ".

Method What it does Example Special errors
s.ljust(width, fillchar=' ') Pad on right (left-justify). "hi".ljust(5, ".")'hi...' TypeError if width not int / fillchar not 1-char str.
s.rjust(width, fillchar=' ') Pad on left (right-justify). "hi".rjust(5, ".")'...hi' Same as ljust.
s.lstrip([chars]) Remove leading whitespace or given chars. t.lstrip()'hi ' TypeError if chars not str/None.
s.rstrip([chars]) Remove trailing whitespace or chars. t.rstrip()' hi' Same.
s.strip([chars]) Remove leading & trailing whitespace or chars. t.strip()'hi' Same.

Searching & counting

Let s = "hello world".

Method What it does Example Special errors
s.count(sub[, start[, end]]) Count occurrences of substring. "hello".count("l")2 – (empty sub is allowed).
s.find(sub[, start[, end]]) First index of sub or -1. "hello".find("l")2 – (never raises on “not found”).
s.rfind(sub[, start[, end]]) Last index of sub or -1. "abcabc".rfind("abc")3
s.index(sub[, start[, end]]) Like find, but raises if not found. "hello".index("e")1 ValueError if sub not found.
s.rindex(sub[, start[, end]]) Like rfind, but raises if not found. "abcabc".rindex("abc")3 ValueError if sub not found.
s.startswith(prefix[, start[, end]]) Test prefix. "hello".startswith("he")True TypeError if prefix is wrong type (must be str or tuple of str).
s.endswith(suffix[, start[, end]]) Test suffix. "hello".endswith("lo")True Same as startswith.

Splitting & joining

Method What it does Example Special errors
s.split(sep=None, maxsplit=-1) Split into list from the left. "a,b,c".split(",")['a','b','c'] TypeError if sep not str/None or maxsplit not int.
s.rsplit(sep=None, maxsplit=-1) Split into list from the right. "a,b,c".rsplit(",", 1)['a,b','c'] Same.
s.splitlines(keepends=False) Split at line boundaries. "a\nb".splitlines()['a','b'] TypeError if keepends not bool.
s.partition(sep) 3-tuple (head, sep, tail) at first sep. "a b c".partition(" ")('a',' ','b c') – (never raises; if not found, returns (s, '', '')).
s.rpartition(sep) 3-tuple at last sep. "a b c".rpartition(" ")('a b',' ','c') Same behavior for “not found”.
sep.join(iterable) Join strings with separator. ",".join(["a","b","c"])'a,b,c' TypeError if any element of iterable is not str (or convertible through __str__ is not used; must actually be str).

Character classification (is* methods)

Return True or False only; they don’t raise exceptions unless the string object itself is invalid (which won’t happen in normal code).

Let s = "abc123".

Method What it checks Example
s.isalnum() All chars alphanumeric, string not empty. "abc123".isalnum()True
s.isalpha() All chars alphabetic, not empty. "abc".isalpha()True
s.isascii() All chars ASCII. "abc".isascii()True
s.isdecimal() All chars are decimal digits. "123".isdecimal()True
s.isdigit() All chars are digits (includes superscripts etc.). "²3".isdigit()True
s.isidentifier() Valid Python identifier. "my_var".isidentifier()True
s.islower() At least one cased char, all cased chars lowercase. "abc".islower()True
s.isnumeric() All chars numeric (includes fractions, etc.). "¾".isnumeric()True
s.isprintable() All chars printable or string empty. "abc\n".isprintable()False
s.isspace() All chars whitespace, not empty. " ".isspace()True
s.istitle() Titlecase (Each Word Like This). "Hello World".istitle()True
s.isupper() At least one cased char, all cased chars uppercase. "ABC".isupper()True

Note: These never raise errors for “content” (e.g. weird Unicode) – they just return True/False

Prefix / suffix helpers (Python 3.9+)

Method What it does Example Special errors
s.removeprefix(prefix) Remove prefix if present. "HelloWorld".removeprefix("Hello")'World' TypeError if prefix not str.
s.removesuffix(suffix) Remove suffix if present. "HelloWorld".removesuffix("World")'Hello' Same.

Translation / replacement

Method What it does Example Special errors / corner cases
s.replace(old, new[, count]) Replace old with new (optionally limit count). "aabb".replace("a","x")'xxbb' TypeError if old/new not str or count not int.
str.maketrans(x, y=None, z=None) Build translation table for translate(). tbl = str.maketrans("ab","xy") ValueError if x and y have different lengths; TypeError for invalid types (e.g. non-str keys that can’t be converted).
s.translate(table) Map chars via translation table. "abc".translate(str.maketrans("ab","xy"))'xyc' TypeError if table isn’t a mapping/sequence with __getitem__; ValueError if mapping gives codepoint out of Unicode range.

Miscellaneous

Method What it does Example Special errors
s.join(iterable) Already covered above under splitting/joining.
s.encode(...) Already covered above.

set – methods & common operations

Method/Operation What it does Example Special errors / corner cases
set() / set(iterable) Create empty set or from iterable. set([1,2,2]) → {1,2} TypeError if argument not iterable. Empty literal is dict, not set: {}{} (dict). Use set() for empty set.
{...} literal Create a set with given elements. {1, 2, 3} {1, 2, 2} → {1,2} (duplicates removed); TypeError: unhashable type: 'list' if you include e.g. [1].
Set comprehension Build set from loop. {x*x for x in range(3)} → {0,1,4} Any error in expression propagates; duplicates automatically removed.
s.add(x) Add element x to set. s.add(3) TypeError: unhashable type: ... if x not hashable (e.g. list, dict).
s.remove(x) Remove element x; must exist. s.remove(2) KeyError if x not in set.
s.discard(x) Remove element if present; else do nothing. s.discard(999) No error if absent.
s.pop() Remove and return an arbitrary element. elem = s.pop() KeyError: pop from an empty set if set is empty. Order not defined.
s.clear() Remove all elements. s.clear() Returns None.
s.copy() Shallow copy of set. s2 = s.copy() Elements themselves are not copied (but they’re typically atomic/hashable anyway).
s.update(*others) Add all elements from other iterable(s). s.update([3,4], {5}) TypeError if any argument is not iterable.
s.union(*others) / `s t` Return new set with elements from all sets/iterables. s.union({3}), `s {3}` Method version accepts any iterable; operator ` requires other operand to be set-like (TypeError` otherwise).
s.intersection(*others) / s & t Common elements of sets/iterables. s & {2,3} Same iterable vs operator rules as above; result is new set.
s.difference(*others) / s - t Elements in s but not in others. s - {1} Method accepts any iterable; operator - needs set-like operand.
s.symmetric_difference(other) / s ^ t Elements in exactly one of the sets. s ^ {2,3} Method accepts any iterable; operator requires set-like operand.
s.intersection_update(*others) / s &= t Keep only intersection (in place). s &= {2,3} Modifies s; same iterable/set requirements as other operators.
s.difference_update(*others) / s -= t Remove elements found in others (in place). s -= {1}
s.symmetric_difference_update(other) / s ^= t In-place symmetric difference. s ^= {2,3}
s.isdisjoint(other) True if two sets share no elements. s.isdisjoint({999}) other can be any iterable; uses membership tests.
s.issubset(other) / s <= t, s < t Subset / proper subset test. s <= {1,2,3} s < t requires s != t; operands should be set-like for operators (else TypeError).
s.issuperset(other) / s >= t, s > t Superset / proper superset test. s >= {1} Same as above.
x in s / x not in s Membership test (hash lookup). 2 in {1,2,3} TypeError only if x is unhashable (very rare; Python usually just uses hash).
for x in s: Iterate over elements (unordered). for x in s: ... Order is arbitrary (implementation-dependent).
len(s) Number of elements. len({1,2,3}) → 3
Equality: s1 == s2 Sets equal if they have same elements. {1,2} == {2,1}True Order doesn’t matter; comparisons like < use subset logic as above; no ordering comparison (s1 < [1,2]TypeError).

dict – methods & common operations

Method/Operation What it does Example Special errors / corner cases
dict() / dict(mapping_or_iterable, **kwargs) Create dictionary. dict(a=1, b=2); dict([("a",1), ("b",2)]) TypeError if iterable elements are not 2-item pairs; keys must be hashable (TypeError: unhashable type: 'list').
{key: value, ...} literal Create dict with given key–value pairs. {"a": 1, "b": 2} Duplicate keys: last one wins ({"a":1,"a":2} → {"a":2}).
Dict comprehension Build dict from loop. {x: x*x for x in range(3)} Key collisions overwrite previous values; expression errors propagate.
d[key] (lookup) Get value for key. {"a":1}["a"] → 1 KeyError if key not present.
d[key] = value (assignment) Set or overwrite value for key. d["a"] = 10 TypeError: unhashable type: ... if key not hashable.
del d[key] Delete entry with given key. del d["a"] KeyError if key not present.
d.get(key[, default]) Return value if key exists, else default/None. d.get("a", 0) Never raises KeyError; only errors from key hashing/equality.
d.setdefault(key[, default]) Return d[key]; if key missing, set to default and return it. d.setdefault("a", 0) Mutates dict when key absent.
d.keys() View of all keys. list(d.keys()) View is dynamic (changes if dict changes).
d.values() View of all values. list(d.values()) Values view not hashable; can’t be used as set elements directly.
d.items() View of (key, value) pairs. for k, v in d.items(): ... Each pair is a tuple; view is dynamic.
d.pop(key[, default]) Remove key and return its value; optional default. d.pop("a") KeyError if key missing and no default; if default given and key missing, returns default instead.
d.popitem() Remove & return an arbitrary key–value pair. k, v = d.popitem() In CPython 3.7+, it’s LIFO (last inserted), but not guaranteed by spec; KeyError if dict is empty.
d.clear() Remove all items. d.clear() Returns None.
d.update(other=..., **kwargs) Merge/update from another mapping/iterable and/or kwargs. d.update({"a":1}, b=2) Later sources override earlier keys; TypeError if iterable items not 2-length; key hashability rules apply.
d.copy() Shallow copy of dict. d2 = d.copy() Nested objects shared between copies.
dict.fromkeys(iterable[, value]) Class method: create new dict with keys from iterable, same value. dict.fromkeys(["a","b"], 0) All keys share same value object (important if value is mutable).
key in d / key not in d Check if key exists. "a" in {"a":1}True Checks keys only (not values).
for k in d: Iterate over keys. for k in d: ... Iteration order preserves insertion order (Python 3.7+).
for k, v in d.items(): Iterate over key–value pairs. for k, v in d.items(): ... Same order as keys.
len(d) Number of key–value pairs. len({"a":1,"b":2}) → 2
Equality: d1 == d2 Dicts equal if they have same keys with equal values. {"a":1,"b":2} == {"b":2,"a":1}True Order doesn’t matter; comparisons like <, > are not supported (TypeError).

defaultdict (from collections) d = defaultdict(int) default 0

Like dict, but missing keys are automatically initialized with a default value produced by a factory function.

Method/Operation What it does Example Special errors / corner cases
defaultdict(default_factory[, mapping_or_iterable]) Create a defaultdict with a factory function. defaultdict(list) default_factory is often list, int, set, etc.; can be None.
dd.default_factory (attribute) The factory function used for new keys. dd.default_factory # int Can be reassigned; if None, missing key access raises KeyError like normal dict.
dd[key] Get value; if key missing, create new default_factory() value and insert it. dd['x'].append(1) when dd is defaultdict(list){'x':[1]} If default_factory is None, missing key → KeyError. If factory call raises error, that error propagates.
dd.get(key[, default]) Like dict .get (does not call default_factory). dd.get('x', 0) No side effect: does not add 'x' to dict.
dd.setdefault(key[, default]) If key exists, return its value; else set it to default and return. dd.setdefault('x', []).append(1) Here, default is used instead of default_factory for that key.
Standard dict methods keys(), values(), items(), update(), pop(), popitem(), clear(), copy() etc. dd.update({'a':1}) Behave as in dict.
Iteration for k in dd: Iterate over keys. for k, v in dd.items(): ... Only sees keys that actually exist (i.e. have been accessed or set).
len(dd) Number of stored keys. len(dd) Doesn’t count “implicit” keys you haven’t touched.
key in dd Check if key exists (not triggering default_factory). 'x' in dd Safe; doesn’t add key or call factory.

OrderedDict (from collections)

Dict subclass that preserves insertion order and adds order-related methods. (Note: regular dict now also preserves insertion order since Python 3.7, but OrderedDict has some extra features.)

od = OrderedDict([('a', 1), ('b', 2)])

Method/Operation What it does Example Special errors / corner cases
OrderedDict() Create empty ordered dict. od = OrderedDict()
OrderedDict(iterable_or_mapping) Create ordered dict, respecting the order of input. OrderedDict([('a',1), ('b',2)]) If from regular dict in 3.7+, it follows dict’s insertion order.
od[key] = value Insert or overwrite key while preserving order. od['c'] = 3 Updating an existing key does not change its position.
del od[key] Remove key–value pair. del od['a'] KeyError if key not present.
od.move_to_end(key, last=True) Move an existing key to either end; last=True → right end, False → left end. od.move_to_end('a') KeyError if key not present.
od.popitem(last=True) Remove and return last item if last=True, first item if False. k, v = od.popitem() KeyError if dict empty.
reversed(od) Iterate over keys in reverse insertion order. for k in reversed(od): ... Implemented via __reversed__.
Equality od1 == od2 In Python 3.7+, equality ignores order; only compares as regular mapping. OrderedDict([('a',1),('b',2)]) == OrderedDict([('b',2),('a',1)])True in 3.7+ Earlier versions (<3.7) considered order in equality.
Standard dict methods keys(), values(), items(), get(), update(), setdefault(), pop() etc. od.items() Preserve insertion order in iteration.
Iteration for k in od: Iterate over keys in insertion order (after moves). for k, v in od.items(): ... Order affected by move_to_end, insertions, deletions.
len(od) Number of key–value pairs. len(od)
key in od Membership on keys. 'a' in od

array (from array module)

Compact, typed sequence of numbers (and Unicode chars with 'u' in some versions).

array (from array module)
Method/Operation What it does Example Special errors / corner cases
array(typecode[, initializer]) Create new array of given type and optional initializer. array('i', [1, 2, 3]) TypeError if initializer has incompatible element types; OverflowError if values out of range for typecode.
Literal-ish (no real literal) There’s no literal syntax like [ ]; must call constructor. array('f', [1.0, 2.5])
a.typecode (attribute) Single char describing element type ('i', 'f', etc.). a.typecode # 'i' Read-only.
a.itemsize (attribute) Size in bytes of one array item. a.itemsize Depends on platform & typecode.
a.append(x) Append a new element to the right. a.append(4) TypeError or OverflowError if x wrong type or out of range.
a.extend(iterable) Append all items from iterable. a.extend([4, 5]) Same errors as append for invalid elements.
a.insert(i, x) Insert x before index i. a.insert(1, 99) Index is clamped to range; type/range errors as in append.
a.pop([i]) Remove and return item at index i (default last). a.pop() IndexError if array empty or index out of range.
a.remove(x) Remove first occurrence of value x. a.remove(2) ValueError if x not found.
a.index(x) Return index of first occurrence of x. a.index(2) ValueError if x not found.
a.count(x) Count occurrences of x. a.count(2) No error if not found (returns 0).
a.reverse() Reverse array in place. a.reverse() Returns None.
a.buffer_info() Low-level (address, length) tuple. addr, length = a.buffer_info() For advanced use; depends on CPython internals.
a.tobytes() Export contents as bytes object. b = a.tobytes() In Py2 it was tostring().
a.tofile(f) Write array to binary file object f. a.tofile(f) Must open file in binary mode; may raise IOError/OSError.
a.tolist() Convert to regular Python list. lst = a.tolist() Always succeeds.
a.frombytes(b) Extend array from bytes representation. a.frombytes(b) Length of b must be multiple of itemsize; otherwise raises ValueError.
a.fromfile(f, n) Read n items from binary file into array. a.fromfile(f, 3) If fewer than n items read → EOFError.
a.fromlist(lst) Extend from list lst. a.fromlist([6,7]) Same type/range checks as extend.
a.tounicode() (type 'u' only) Convert to a Unicode string (if supported). array('u', 'hi').tounicode() Only valid for Unicode type arrays; otherwise AttributeError.
a[i] / a[i] = x Indexing / assignment. a[0] = 10 IndexError if out of range; type & range errors as usual.
a[start:stop:step] Slice; returns new array or list? → new array. a[1:3] Slice assignment (a[1:3] = array('i', [7,8])) must match typecode; assignment length can differ.
len(a) Number of elements. len(a)
x in a Membership test (==). 2 in a Linear search.
Iteration for x in a: Iterate over elements. for x in a: ...
a1 + a2 Concatenate arrays with same typecode. array('i',[1]) + array('i',[2,3]) TypeError if typecodes differ.
a * n Repeat array n times. array('i',[1,2])*3 TypeError if n not int; 0 or negative n → empty array.

Counter (multiset, from collections) c = Counter("abracadabra")

Method/Operation What it does Example Special errors / corner cases
Counter() Create empty counter. c = Counter()
Counter(iterable) Count elements from iterable. Counter("aba") → {'a':2, 'b':1} Elements become keys; counts are ints.
Counter(mapping) From mapping of element → count. Counter({'a': 3, 'b': 1}) Non-int values are allowed but conceptually counts.
c.elements() Iterator over elements, repeating each as many times as its count (positive only). list(Counter(a=2, b=-1).elements()) → ['a','a'] Ignores zero or negative counts.
c.most_common([n]) List of (elem, count) sorted descending by count. c.most_common(2) If n omitted → all elements; if n larger than unique elements → returns all.
c.subtract(iterable_or_mapping) Subtract counts from c in place. c.subtract("aba") Counts may go negative; no error.
c.update(iterable_or_mapping) Add counts to c in place. c.update("aba") Similar to dict.update but adds counts.
c.total() (3.10+) Sum of counts (values). Counter('ab').total() Includes negative counts too.
c.clear() Remove all elements. c.clear()
c.copy() Shallow copy of counter. c2 = c.copy()
c[key] Get count for key; missing keys default to 0. c['z'] # 0 No KeyError; behaves like defaultdict(int).
del c[key] Remove an element entirely. del c['a'] KeyError if key missing.
Arithmetic: c1 + c2 Add counts; discard zero/negative results. Counter(a=2) + Counter(a=-1,b=1)Counter(a=1,b=1) Only keeps positive counts.
c1 - c2 Subtract counts; keep only positive results. Counter(a=2,b=1) - Counter(a=1,b=2)Counter(a=1) Negative/zero results are discarded.
c1 & c2 Intersection: min of counts (only positive). Counter(a=2,b=1) & Counter(a=1,b=3)Counter(a=1,b=1) Counts ≤ 0 removed.
`c1 c2` Union: max of counts. `Counter(a=2,b=1) Counter(a=3,b=0)Counter(a=3,b=1)`
Standard dict methods keys(), values(), items(), get(), pop(), popitem(), setdefault(), update() etc. c['a'], "a" in c, len(c) Behave like dict but with counts; values() may contain negative numbers.
len(c) Number of distinct elements. len(Counter('aba')) → 2 Not total count; for that use c.total() or sum(c.values()).
Iteration for k in c: Iterate over unique keys. for elem in c: Order: insertion order-ish since 3.7, but still mostly treat as mapping.

ChainMap (from collections) cm = ChainMap({'a': 1}, {'b': 2})

Groups multiple dicts (or mappings) into a single “view”; lookups search them in order.

Method/Operation What it does Example Special errors / corner cases
ChainMap(*maps) Create chain of one or more mappings. cm = ChainMap(d1, d2, d3) If no maps given, creates a single empty dict.
cm.maps (attribute) List of underlying mappings (from first to last). cm.maps Mutating these dicts changes the ChainMap view.
cm.new_child(m=None) Return a new ChainMap with a new dict (or given map) at the front. child = cm.new_child({'x': 9}) Does not modify existing ChainMap; returns a new one.
cm.parents (property) New ChainMap of all maps except the first. parent_cm = cm.parents If only one map, parents is an empty ChainMap.
cm[key] Lookup key: search first map, then next, etc. cm['a'] KeyError if key not found in any map.
cm.get(key[, default]) Lookup with default; search all maps. cm.get('z', 0) No KeyError; returns default if not found.
cm[key] = value Write to first mapping only. cm['a'] = 10 Does not affect later maps, even if they contained a.
del cm[key] Delete key from first mapping. del cm['a'] KeyError if key not in first map (even if present in later ones).
cm.keys() View of all keys from all maps (left bias). cm.keys() If same key appears multiple times, first one “wins”.
cm.values() Values matching keys() ordering. cm.values() Values come from first map that has the key.
cm.items() (key, value) pairs. cm.items() Duplicate keys appear only once, from earliest map.
len(cm) Number of distinct keys. len(cm) If a key appears in multiple maps, it’s counted once.
Iteration for k in cm: Iterate over keys. for k in cm: Order is based on chain order; duplicates removed.
Update via cm.update(mapping_or_iterable) Update only the first mapping. cm.update({'a': 99, 'z': 1}) Later maps unaffected.