Python Reference

A searchable reference for the methods and built-in functions you use every day. Every entry shows the syntax, what it returns, a runnable example with its real output, and the mistakes people make most often. Pair it with the Python tutorial when you want the full explanation.

List methods

Python List append() Method
`list.append(item)` adds **one** item to the end of a list, changes the list in place and returns `None`.
Python List extend() Method
`list.extend(iterable)` adds **every item** of an iterable (list, tuple, string, set, range...) to the end of the list, changes t…
Python List insert() Method
`list.insert(index, item)` puts `item` **before** the position `index`, shifts the later items one place to the right, changes th…
Python List remove() Method
`list.remove(value)` deletes the **first** item equal to `value`, changes the list in place and returns `None`; it raises `ValueE…
Python List pop() Method
`list.pop(index=-1)` removes the item at `index` (the last item by default) **and returns it**; it raises `IndexError` for an emp…
Python List clear() Method
`list.clear()` removes **all** items from a list in place, leaving the same list object empty, and returns `None`.
Python List index() Method
`list.index(value, start, stop)` returns the position of the **first** item equal to `value`, and raises `ValueError` if the valu…
Python List count() Method
`list.count(value)` returns how many items in the list are equal to `value`, or `0` if there are none; it never changes the list.
Python List sort() Method
`list.sort(key=None, reverse=False)` sorts the list **in place** in ascending order, is stable, and returns `None`; use `sorted()…
Python List reverse() Method
`list.reverse()` flips the order of the items in a list **in place** and returns `None`; it does not sort anything.
Python List copy() Method
`list.copy()` returns a new, **shallow** copy of the list: a separate list holding the same items, so changing one list does not …

String methods

Python String split() Method
`str.split(sep=None, maxsplit=-1)` cuts a string into pieces and returns them as a **list of strings**; with no `sep` it splits o…
Python String join() Method
`separator.join(iterable)` glues every string in the iterable together into **one string**, placing `separator` between neighbour…
Python String strip() Method
`text.strip(chars=None)` returns a **new string** with leading and trailing whitespace removed, or with any characters listed in …
Python String lstrip() Method
`text.lstrip(chars=None)` returns a new string with **leading** (left-hand) whitespace, or any characters in `chars`, removed; th…
Python String rstrip() Method
`text.rstrip(chars=None)` returns a new string with **trailing** (right-hand) whitespace, or any characters in `chars`, removed; …
Python String replace() Method
`text.replace(old, new, count=-1)` returns a **new string** in which every occurrence of `old` is replaced by `new`, or only the …
Python String upper() Method
`text.upper()` returns a **new string** with every lowercase letter converted to uppercase; digits, spaces and symbols stay the s…
Python String lower() Method
`text.lower()` returns a **new string** with every uppercase letter converted to lowercase; characters without case are unchanged.
Python String title() Method
`text.title()` returns a **new string** in which the first letter of every word is uppercase and all other letters are lowercase.
Python String capitalize() Method
`text.capitalize()` returns a **new string** with the first character in uppercase and **all remaining characters in lowercase**.
Python String swapcase() Method
`text.swapcase()` returns a **new string** in which every uppercase letter becomes lowercase and every lowercase letter becomes u…
Python String find() Method
`text.find(sub, start=0, end=len(text))` returns the **lowest index** where `sub` occurs, or **`-1`** if it does not occur; it ne…
Python String index() Method
`str.index(sub)` returns the position of the **first** occurrence of `sub` in a string, and raises `ValueError` if `sub` is not f…
Python String count() Method
`str.count(sub)` returns how many **non-overlapping** times `sub` appears in a string. It returns `0` when there is no match and …
Python String startswith() Method
`str.startswith(prefix)` returns `True` if the string begins with `prefix` and `False` otherwise. Pass a **tuple** of prefixes to…
Python String endswith() Method
`str.endswith(suffix)` returns `True` if the string finishes with `suffix` and `False` otherwise. Pass a **tuple** to test severa…
Python String format() Method
`str.format()` fills `{}` placeholders in a string with the values you pass in, for example `"Hi {}".format("Asha")` gives `'Hi A…
Python String isdigit() Method
`str.isdigit()` returns `True` if the string is **not empty** and every character is a digit. `"123"` passes; `"-5"`, `"3.14"` an…
Python String isalpha() Method
`str.isalpha()` returns `True` if the string is **not empty** and every character is a letter. Spaces, digits, hyphens and punctu…
Python String isalnum() Method
`str.isalnum()` returns `True` if the string is **not empty** and every character is a letter or a digit. Spaces, underscores and…
Python String center() Method
`str.center(width, fillchar)` returns a new string of length `width` with the original text in the middle, padded on both sides w…
Python String zfill() Method
`str.zfill(width)` pads a string on the left with zeros until it is `width` characters long, for example `"42".zfill(5)` gives `'…
Python String splitlines() Method
`str.splitlines()` splits a string at line boundaries and returns a list of the lines, without the line-break characters unless y…
Python String partition() Method
`str.partition(sep)` splits a string at the **first** occurrence of `sep` and always returns a tuple of three parts: the text bef…

Dictionary methods

Python Dictionary get() Method
`dict.get(key, default=None)` returns the value for `key` if it exists, otherwise `default` (which is `None` unless you pass some…
Python Dictionary items() Method
`dict.items()` returns a live view of the dictionary's `(key, value)` pairs, most often used as `for key, value in d.items():` to…
Python Dictionary keys() Method
`dict.keys()` returns a live, read-only view of all the keys in a dictionary, in insertion order. Convert it with `list()` when y…
Python Dictionary values() Method
`dict.values()` returns a live view of all the values stored in a dictionary, in insertion order, ready to loop over or pass to `…
Python Dictionary update() Method
`dict.update(other)` copies every key-value pair from `other` into the dictionary, overwriting keys that already exist, changes t…
Python Dictionary pop() Method
`dict.pop(key[, default])` removes `key` from the dictionary and returns its value. If the key is missing it returns `default`, o…
Python Dictionary popitem() Method
`dict.popitem()` removes the most recently inserted key-value pair from a dictionary and returns it as a `(key, value)` tuple. On…
Python Dictionary setdefault() Method
`dict.setdefault(key, default=None)` returns the value for `key` if it exists; otherwise it stores `default` under `key` and retu…
Python Dictionary clear() Method
`dict.clear()` removes all key-value pairs from a dictionary in place, leaving it empty, and returns `None`. Every variable that …
Python Dictionary copy() Method
`dict.copy()` returns a new dictionary with the same keys and values. It is a **shallow** copy: the top level is independent, but…
Python Dictionary fromkeys() Method
`dict.fromkeys(keys, value=None)` is a class method that builds a new dictionary whose keys come from `keys`, all given the same …

Set methods

Python Set add() Method
`set.add(element)` inserts **one** element into a set in place and returns `None`. If the element is already in the set, nothing …
Python Set remove() Method
`set.remove(element)` deletes the element from the set in place and returns `None`. If the element is **not** in the set it raise…
Python Set discard() Method
`set.discard(element)` removes the element from the set if it is present and does nothing if it is not. It always returns `None` …
Python Set pop() Method
`set.pop()` removes one **arbitrary** element from the set and returns it. On an empty set it raises `KeyError`.
Python Set union() Method
`a.union(b)` returns a **new** set containing every element that is in `a`, in `b`, or in both. The original sets are not changed.
Python Set intersection() Method
`a.intersection(b)` returns a **new** set with only the elements that appear in both `a` and `b`. The original sets are unchanged.
Python Set difference() Method
`a.difference(b)` returns a **new** set of the elements that are in `a` but **not** in `b`. The order of the sets matters, and th…
Python Set symmetric_difference() Method
`a.symmetric_difference(b)` returns a **new** set of elements that are in `a` or in `b` but **not in both**. It is the same as `a…
Python Set update() Method
`set.update(*iterables)` adds every item of each iterable into the set **in place** and returns `None`. Duplicates are ignored.
Python Set issubset() Method
`a.issubset(b)` returns `True` if **every** element of `a` is also in `b`, otherwise `False`. It is the same test as `a <= b`.
Python Set clear() Method
`set.clear()` removes **all** elements from the set in place and returns `None`. The set object still exists afterwards, but it i…

Tuple methods

Python Tuple count() Method
`tuple.count(value)` returns how many items in the tuple are equal to `value`, or `0` if there are none. It is one of only two tu…
Python Tuple index() Method
`tuple.index(value, start, stop)` returns the position of the **first** item equal to `value` and raises `ValueError` if the valu…

Built-in functions

Python print() Function
`print(*objects, sep=' ', end='\n')` converts each value to text, joins them with `sep`, writes the result followed by `end` and …
Python len() Function
`len(obj)` returns the number of items in a container as an `int`: characters in a string, elements in a list or tuple, keys in a…
Python range() Function
`range(start, stop, step)` produces a sequence of integers from `start` up to, but not including, `stop`; with one argument, `ran…
Python type() Function
`type(obj)` returns the class of an object, such as `` or ``, so you can see what kind of value a variable holds.
Python int() Function
`int(x)` converts a number or a numeric string to an integer, cutting off any decimal part; `int(text, base)` reads text in anoth…
Python float() Function
`float(x)` converts an integer or a numeric string such as `'3.14'` into a floating-point number; `float()` with no argument retu…
Python str() Function
`str(obj)` returns the readable text form of any object, so `str(42)` is `'42'` and `str([1, 2])` is `'[1, 2]'`.
Python input() Function
`input(prompt)` shows the prompt, waits for the user to type a line and press Enter, and returns what was typed as a **string**.
Python sum() Function
`sum(iterable, start=0)` adds up all the items of an iterable and returns the total; an empty iterable gives `start`, which is `0…
Python min() Function
`min(iterable)` or `min(a, b, ...)` returns the smallest item; use `key=` to decide how items are compared and `default=` to avoi…
Python max() Function
`max(iterable)` or `max(a, b, ...)` returns the largest item; use `key=` to choose what to compare and `default=` to avoid an err…
Python sorted() Function
`sorted(iterable, key=None, reverse=False)` returns a **new** sorted list and leaves the original untouched; it works on any iter…
Python reversed() Function
`reversed(seq)` returns an **iterator** that walks a sequence from the last item to the first, without changing the original and …
Python enumerate() Function
`enumerate(iterable, start=0)` wraps an iterable so a `for` loop receives `(index, item)` pairs, counting from `start`.
Python zip() Function
`zip(*iterables, strict=False)` combines items from several iterables into tuples, stopping when the shortest one runs out.
Python map() Function
`map(function, iterable, ...)` calls `function` on every item of the iterable and returns an iterator of the results.
Python filter() Function
`filter(function, iterable)` returns an iterator of the items for which `function(item)` is truthy.
Python abs() Function
`abs(x)` returns the absolute value of a number: its distance from zero, so `abs(-7)` is `7`.
Python round() Function
`round(number, ndigits=None)` rounds a number to `ndigits` decimal places, or to the nearest integer when `ndigits` is omitted; e…
Python any() Function
`any(iterable)` returns `True` if **at least one** item of the iterable is truthy, and `False` if none are or the iterable is emp…
Python all() Function
`all(iterable)` returns `True` if **every** item of the iterable is truthy (or the iterable is empty), and `False` as soon as it …
Python isinstance() Function
`isinstance(obj, classinfo)` returns `True` if `obj` is an instance of the class (or of any class in a tuple of classes), includi…
Python open() Function
`open(file, mode='r', encoding=None)` opens a file and returns a file object you can read from or write to; use it in a `with` bl…
Python divmod() Function
`divmod(a, b)` returns the tuple `(a // b, a % b)`: the floor quotient and the remainder from a single division.
Python pow() Function
`pow(base, exp, mod=None)` returns `base` raised to the power `exp`; with `mod` it returns `(base ** exp) % mod` computed efficie…
Python chr() Function
`chr(i)` returns the one-character string whose Unicode code point is the integer `i`, so `chr(65)` is `"A"`.
Python ord() Function
`ord(c)` returns the Unicode code point (an integer) of a one-character string, so `ord("A")` is `65`.

Explore more

Python ProgramsPython ComparisonsPython How-To GuidesPython Cheat SheetsPython glossaryPython tutorial