Python built-in types and functions

dict, list, str, set, and selected built-in functions, with signatures, gotchas, and a dictionary comparison example.

モジュールページの本文は現在英語です。

Built-in types and functions are available without an import. They are part of the language, not of a standard-library module and not of a third-party package.

This page documents the operations used most often in everyday Python, not every method on these types. For the complete list, use the official documentation linked from each section.

Examples were checked against Python 3.13. See the official documentation for the complete API.

Python reference overview →

dict

A dict maps hashable keys to values. In Python 3.7 and later, insertion order is part of the language specification. Key views support set operations, which is often clearer than looping over keys by hand.

dict.get(key, default) returns default when the key is missing. It cannot tell a missing key from a key whose value is the default. Use `key in mapping` or KeyError when that distinction matters.

dict.get

d.get(key, default=None)

Return the value for key if it is present, otherwise return default.

ParameterDescription
keyThe key to look up.
defaultValue returned when the key is absent. Defaults to None.

Returns: The stored value, or default if the key is missing. This method does not raise KeyError.

  • d[key] raises KeyError when the key is missing. get() does not.
  • If the stored value can also be None (or whatever you used as default), check membership first.
python
config = {"port": 80, "host": None}
print(config.get("port"))
print(config.get("debug", False))
print("host" in config, config.get("host"))
print("debug" in config, config.get("debug"))

Expected output

80
False
True None
False None

Related: Compare dictionary keys and values, Official dict methods

Official documentation →

Compare dictionary keys and values

d.keys()  |  d.items()  |  d.values()

The key and item views of a dict support union, intersection, and difference. Use them to report added, removed, and changed keys in a stable order.

  • Compare values only for keys present in both dictionaries.
  • Sorting the three lists keeps the report stable even though dict iteration is insertion-ordered.
  • This example is the original Python reference recipe; the section id is unchanged.
python
before = {"port": 80, "host": "localhost"}
after = {"port": 8080, "debug": False}

print("added:", sorted(after.keys() - before.keys()))
print("removed:", sorted(before.keys() - after.keys()))
changed = [key for key in before.keys() & after.keys() if before[key] != after[key]]
print("changed:", sorted(changed))

Expected output

added: ['debug']
removed: ['host']
changed: ['port']

Related: Official dictionary view objects

Official documentation →

list

A list is an ordered, mutable sequence. An out-of-range index raises IndexError. A slice that overshoots the end is simply shorter.

list.sort() sorts in place and returns None. sorted() returns a new list and works on any iterable.

list.sort and sorted

list.sort(*, key=None, reverse=False)
sorted(iterable, /, *, key=None, reverse=False)

Sort a list in place, or build a new sorted list from any iterable.

ParameterDescription
keyOptional function that maps each item to a sort key.
reverseIf True, sort in descending order.

Returns: list.sort() returns None. sorted() returns a new list.

Raises

  • TypeError — Raised when items cannot be compared, for example mixing int and str under the default ordering.
python
rows = ["pear", "Apple", "apple"]
print(sorted(rows))
print(sorted(rows, key=str.lower))
rows.sort()
print(rows)

Expected output

['Apple', 'apple', 'pear']
['Apple', 'apple', 'pear']
['Apple', 'apple', 'pear']

Official documentation →

str

Strings are immutable sequences of Unicode characters. Methods such as split, join, and strip return new strings; they do not modify the original.

str.split() with no arguments splits on any whitespace and drops empty tokens. split(" ") treats every space as a separator and can keep empty strings.

str.split and str.join

str.split(sep=None, maxsplit=-1)
str.join(iterable)

Split a string into a list of substrings, or join an iterable of strings with a separator.

ParameterDescription
sepDelimiter. None (the default) splits on whitespace and discards empty results.
maxsplitMaximum number of splits. -1 means no limit.
iterableFor join, an iterable of strings. Non-string items raise TypeError.

Returns: split() returns a list of strings. join() returns a single string.

Raises

  • TypeError — str.join() raises TypeError if an item is not a string.
python
line = "  apple  pear\t"
print(line.split())
print("a  b".split(" "))
print(",".join(["apple", "pear"]))

Expected output

['apple', 'pear']
['a', '', 'b']
apple,pear

Official documentation →

set

A set is an unordered collection of unique, hashable elements. Use it for membership tests and set algebra, not for counting or for preserving duplicates. For frequencies, use collections.Counter.

set operations

s | t    s & t    s - t    s ^ t    value in s

Union, intersection, difference, symmetric difference, and membership are supported as operators and as methods.

  • Sets drop duplicates. They are the wrong structure when counts matter.
  • Elements must be hashable. A list cannot be added to a set; a tuple can if its items are hashable.
python
before = {"apple", "pear"}
after = {"pear", "kiwi"}
print("added:", sorted(after - before))
print("removed:", sorted(before - after))
print("shared:", sorted(before & after))

Expected output

added: ['kiwi']
removed: ['apple']
shared: ['pear']

Related: Counter

Official documentation →

Selected built-in functions

These functions live in the built-in namespace. They are not methods, and they are not imported from a module. open() is a built-in, but pathlib.Path is usually clearer for path operations; see the pathlib page.

len, sorted, enumerate, zip, isinstance

len(s)
sorted(iterable, /, *, key=None, reverse=False)
enumerate(iterable, start=0)
zip(*iterables, strict=False)
isinstance(object, classinfo)

Common built-in helpers for length, ordering, indexed iteration, parallel iteration, and type checks.

  • zip() stops at the shortest input unless strict=True, which raises ValueError when lengths differ. strict was added in Python 3.10.
  • isinstance(value, typ) is preferred over type(value) is typ because it accepts subclasses.
python
names = ["ada", "grace"]
print(len(names))
print(list(enumerate(names, start=1)))
print(list(zip(names, [1, 2, 3])))
print(isinstance({"port": 80}, dict))
try:
    list(zip(names, [1], strict=True))
except ValueError as exc:
    print(type(exc).__name__)

Expected output

2
[(1, 'ada'), (2, 'grace')]
[('ada', 1), ('grace', 2)]
True
ValueError

Official documentation →