Python reference
143 pages on Python's built-in functions, the methods of strings, lists, dictionaries and sets, and the statements every program is made of. Each one has examples you can run and change in the page.
Built-in functions49Functions you can use anywhere without importing anything: print, len, range, input, sorted and more.String methods33Clean, split, search and reformat text: split, join, strip, replace, find, upper and more.List methods11Add, remove, sort and search the items of a list: append, extend, pop, sort and more.Dictionary methods11Look up, loop over and update key-value pairs: get, items, keys, update, pop and more.Set methods13Unique items and set maths: add, discard, union, intersection, difference and more.Statements and syntax26The building blocks of every program: if, for, while, def, try, with, comprehensions and f-strings.
Most searched
all()Returns True when every item in a list or other iterable is true, and False as soon as one item is false. An empty iterable gives True.any()Returns True when at least one item in a list or other iterable is true, and False when every item is false or the iterable is empty.chr()Turns a Unicode code point, a whole number such as 65, into the character it stands for, such as A. It is the opposite of ord().class statementclass defines a new type of object that bundles data (attributes) and the functions that work on it (methods) under one name.def (functions)def creates a function: a named block of code you can run again and again with different inputs, and that can return a result.dict.get()Returns the value for a key, or a default value (None unless you give one) when the key is missing, instead of raising KeyError.dict.items()Returns a live view of a dictionary's key-value pairs as tuples, so you can loop over the key and its value together.dict.keys()Returns a live view of a dictionary's keys, in the order they were added. Loop over it, test it with in, or turn it into a list.dict.pop()Removes a key from a dictionary and returns its value. Give a default to avoid a KeyError when the key is missing.dict.update()Adds the keys and values from another dictionary (or from pairs or keyword arguments), replacing values for keys already there.enumerate()Adds a counter to any loop, giving you each item's position and the item itself, so you never need range(len(...)) again.f-stringsAn f-string puts variables and expressions straight into text with {curly braces}, and can format numbers, dates and widths.for loopA for loop runs the same block of code once for every item in a list, string, range or any other collection.format()Turns a value into nicely formatted text with a format spec: decimals, thousands separators, percentages, padding, alignment or binary.if statementAn if statement runs a block of code only when a condition is true, with elif and else for the other cases.import statementimport loads a module so you can use its functions, such as math.sqrt() or random.choice(), from the standard library or your own files.input()Shows an optional prompt, waits for the user to type a line and press Enter, and returns what they typed as a string.int()Turns text like "42" or a decimal number like 3.9 into a whole number, and can read binary, hexadecimal and other bases too.lambdalambda makes a small, nameless function in one expression. It is most useful as a key for sorted(), min(), max() and similar.len()Returns how many items something holds: characters in a string, elements in a list or tuple, keys in a dictionary or members of a set.list comprehensionA list comprehension builds a new list from another collection in one readable line, with an optional filter to keep only some items.list.append()Adds a single item to the end of a list. The list changes in place and the method itself gives back None.list.extend()Adds every item from another list, tuple, string or other iterable to the end of a list, one by one, in place.list.insert()Puts a new item into a list at the position you choose, moving the items after it one place to the right.list.pop()Removes an item from a list by position and gives it back to you. With no argument it takes the last item.list.remove()Deletes the first item in a list that equals the value you give. Raises ValueError when no item matches.list.sort()Puts the items of a list in order, smallest first by default. It changes the list itself and returns None.map()Calls a function on every item of a list or other iterable and gives back the results, for example to turn a list of strings into numbers.max()Returns the largest item of a list or of several arguments, with a key function to choose what to compare and a default for empty data.min()Returns the smallest item of a list or of several arguments, with a key function to decide what smallest means and a default for empty data.open()Opens a file so you can read its text, write new text, or add lines to the end. Use it with a with block so the file closes itself.ord()Turns one character into its Unicode code point, the whole number that stands for it, such as 65 for A. chr() goes the other way.print()Writes text, numbers and any other values to the screen, with control over the separator, the line ending and where the output goes.range()Produces a sequence of whole numbers from a start to an end, with an optional step, mostly used to repeat a for loop a set number of times.return statementreturn ends a function and sends a value back to the code that called it. Without a value, or without return, you get None.round()Rounds a number to the nearest whole number or to a chosen number of decimals, with two surprises: halves go to the even side and floats are not exact.slicing [start:stop:step]Slicing takes a part of a list, string or tuple with [start:stop:step]: the start is included, the stop is not, and step skips items.sorted()Returns a new sorted list from any collection, smallest first or reversed, with a key function to sort by length, by a field or ignoring case.str()Turns numbers, lists and any other value into readable text, so you can join it with other strings, print it or save it to a file.str.count()Counts how many times a piece of text appears in a string, without overlaps, in the whole string or in a part of it.str.find()Returns the position where a piece of text first appears in a string, or -1 when it is not there at all.str.format()Fills values into the {} placeholders of a string, with control over decimals, width, alignment and thousand separators.str.isdigit()Returns True when a string is not empty and every character is a digit. Useful for checking input before int().str.join()Glues the strings in a list (or any iterable) into one string, with the text you call it on placed between every piece.str.lower()Returns a copy of a string with every capital letter turned into a small (lower-case) letter. Useful for comparing text.str.replace()Returns a copy of a string where every match of one piece of text is swapped for another, or only the first few matches.str.split()Cuts a string into a list of pieces: into words by default, or at any separator you choose, such as a comma.str.startswith()Returns True when a string begins with the text you give, or with any one of several options passed as a tuple.str.strip()Removes spaces, tabs and new lines from the start and end of a string, or any set of characters you list.str.upper()Returns a copy of a string with every letter turned into a capital (upper-case) letter. Digits and symbols stay the same.sum()Adds up all the numbers in a list, tuple or any other iterable, with an optional starting value, in one short and fast call.try / except / else / finallytry runs code that might fail; except catches the error so your program can react, and else and finally add extra steps.type()Tells you the type of any value, such as int, str, list or dict, which helps when a program does not behave the way you expect.while loopA while loop repeats a block of code as long as its condition stays true, for when you do not know how many rounds you need.zip()Pairs up items from two or more lists by position, so you can loop over them together, build a dictionary, or split pairs apart again.
A to Z
- abs()Returns the absolute value of a number, its distance from zero without a minus sign, useful for differences, distances and tolerances.
- set.add()Puts one element into a set. If the element is already there, nothing happens: a set never holds duplicates.
- all()Returns True when every item in a list or other iterable is true, and False as soon as one item is false. An empty iterable gives True.
- and, or, not (logical operators)and, or and not combine and flip conditions: and needs both sides true, or needs one, and not turns True into False.
- any()Returns True when at least one item in a list or other iterable is true, and False when every item is false or the iterable is empty.
- list.append()Adds a single item to the end of a list. The list changes in place and the method itself gives back None.
- assert statementassert checks a condition that should always be true and stops with an AssertionError when it is not. Ideal for tests and sanity checks.
- bin()Converts a whole number to a binary string that starts with 0b, such as 0b1010 for 10. Use int(text, 2) to convert back.
- bool()Tells you whether Python treats a value as true or false: empty things and zero are False, almost everything else is True.
- break statementbreak stops a for or while loop immediately and jumps to the first line after it, skipping the rest of the rounds.
- bytes()Creates a bytes object, an unchangeable sequence of numbers from 0 to 255, used for files, network data and encoded text.
- callable()Returns True if an object can be called with brackets, like a function, method or class, and False for plain values such as numbers.
- str.capitalize()Returns a copy of a string with its first character in capitals and all the other letters turned into small letters.
- str.casefold()Returns a version of a string made for case-insensitive comparison. Stronger than lower() for text in any language.
- str.center()Returns a copy of a string centred in a field of the width you choose, padded with spaces or another single character.
- chr()Turns a Unicode code point, a whole number such as 65, into the character it stands for, such as A. It is the opposite of ord().
- class statementclass defines a new type of object that bundles data (attributes) and the functions that work on it (methods) under one name.
- list.clear()Empties a list in place, so the same list object ends up with no items. Every variable pointing to it sees the change.
- dict.clear()Deletes every key and value from a dictionary in place. Every variable that refers to the same dictionary sees it empty.
- set.clear()Empties a set in place, leaving set(). Every variable that refers to the same set sees it empty afterwards.
- continue statementcontinue skips the rest of the current loop round and jumps straight to the next one, without ending the loop.
- list.copy()Returns a new list with the same items. Changing the copy's length or items does not touch the original, but nested lists stay shared.
- dict.copy()Returns a new dictionary with the same keys and values. Adding keys to the copy leaves the original alone, but nested values stay shared.
- str.count()Counts how many times a piece of text appears in a string, without overlaps, in the whole string or in a part of it.
- list.count()Counts how many items in a list are equal to a given value and returns that number. Gives 0 when there are none.
- def (functions)def creates a function: a named block of code you can run again and again with different inputs, and that can return a result.
- del statementdel removes a name, a list item, a slice of a list or a dictionary key. It deletes the reference, not necessarily the object itself.
- dict()Builds a dictionary from keyword arguments, from a list of key-value pairs, from two lists zipped together, or as a copy of another dictionary.
- dict comprehensionA dict comprehension builds a new dictionary in one line from any collection, choosing each key and value, with an optional filter.
- set.difference()Returns a new set with the elements of this set that are not in any of the others. Same as the - operator.
- dir()Lists the names of the attributes and methods an object has, sorted alphabetically. With no argument, lists the names in the current scope.
- set.discard()Removes an element from a set if it is there, and silently does nothing if it is not. It never raises an error.
- divmod()Divides two numbers and returns both the whole-number result and the remainder as a pair, the same as (a // b, a % b).
- str.encode()Converts a string into bytes using a text encoding, UTF-8 by default, ready for files, networks or hashing.
- str.endswith()Returns True when a string ends with the text you give, or with any one of several endings passed as a tuple.
- enumerate()Adds a counter to any loop, giving you each item's position and the item itself, so you never need range(len(...)) again.
- eval()Evaluates a string as a Python expression and returns the result. Powerful but dangerous with untrusted text: prefer ast.literal_eval().
- list.extend()Adds every item from another list, tuple, string or other iterable to the end of a list, one by one, in place.
- f-stringsAn f-string puts variables and expressions straight into text with {curly braces}, and can format numbers, dates and widths.
- filter()Goes through a list or other iterable and keeps only the items for which a test function returns true, or with None, only the truthy items.
- str.find()Returns the position where a piece of text first appears in a string, or -1 when it is not there at all.
- float()Turns text like "3.14" or a whole number into a floating-point number, the type Python uses for prices, measurements and other decimals.
- for loopA for loop runs the same block of code once for every item in a list, string, range or any other collection.
- format()Turns a value into nicely formatted text with a format spec: decimals, thousands separators, percentages, padding, alignment or binary.
- str.format()Fills values into the {} placeholders of a string, with control over decimals, width, alignment and thousand separators.
- dict.fromkeys()Builds a new dictionary whose keys come from a list or other iterable, all set to the same value (None by default).
- frozenset()Creates a frozenset: a set that can never change after it is made, so it can be a dictionary key or an item inside another set.
- dict.get()Returns the value for a key, or a default value (None unless you give one) when the key is missing, instead of raising KeyError.
- getattr()Reads an attribute of an object when the attribute name is in a string, with an optional default value if the attribute is missing.
- global and nonlocalglobal lets a function change a variable defined at the top of the file; nonlocal lets an inner function change one from the outer function.
- hasattr()Returns True if an object has an attribute or method with the given name, and False if not. The name is passed as a string.
- help()Shows the documentation of a function, class or module: its parameters and its docstring. Most useful in the interactive Python console.
- hex()Converts a whole number to a hexadecimal string that starts with 0x, such as 0xff for 255. Use int(text, 16) to convert back.
- if statementAn if statement runs a block of code only when a condition is true, with elif and else for the other cases.
- import statementimport loads a module so you can use its functions, such as math.sqrt() or random.choice(), from the standard library or your own files.
- in operator (membership)The in operator checks whether a value is inside a list, string, dictionary or set, and gives True or False. not in checks the opposite.
- str.index()Returns the position where a piece of text first appears in a string, and raises ValueError when it is not found.
- list.index()Returns the position of the first item equal to a value. Raises ValueError when the value is not in the list.
- input()Shows an optional prompt, waits for the user to type a line and press Enter, and returns what they typed as a string.
- list.insert()Puts a new item into a list at the position you choose, moving the items after it one place to the right.
- int()Turns text like "42" or a decimal number like 3.9 into a whole number, and can read binary, hexadecimal and other bases too.
- set.intersection()Returns a new set with only the elements that appear in this set and in every other one given. Same as the & operator.
- is operator (identity vs ==)is checks whether two names point to the very same object, while == checks whether two values are equal. Use is mainly with None.
- str.isalnum()Returns True when a string is not empty and every character is a letter or a number. Spaces and symbols make it False.
- str.isalpha()Returns True when a string is not empty and every character is a letter, in any alphabet. Spaces and digits make it False.
- str.isdigit()Returns True when a string is not empty and every character is a digit. Useful for checking input before int().
- set.isdisjoint()Returns True when this set and the other collection have no element in common, and False as soon as one is shared.
- isinstance()Checks whether a value is of a given type, or of one of several types, and also accepts subclasses, which makes it the right way to test types.
- str.isnumeric()Returns True when every character is a number of some kind: digits, superscripts, fractions like ½ or Roman numerals.
- str.isspace()Returns True when a string is not empty and holds only whitespace: spaces, tabs, new lines and similar blank characters.
- set.issubset()Returns True when every element of this set is also in the other collection. Same as the <= operator for two sets.
- set.issuperset()Returns True when this set contains every element of the other collection. Same as the >= operator for two sets.
- dict.items()Returns a live view of a dictionary's key-value pairs as tuples, so you can loop over the key and its value together.
- iter()Returns an iterator, an object that hands out the items of a list, string or file one at a time each time you call next() on it.
- str.join()Glues the strings in a list (or any iterable) into one string, with the text you call it on placed between every piece.
- dict.keys()Returns a live view of a dictionary's keys, in the order they were added. Loop over it, test it with in, or turn it into a list.
- lambdalambda makes a small, nameless function in one expression. It is most useful as a key for sorted(), min(), max() and similar.
- len()Returns how many items something holds: characters in a string, elements in a list or tuple, keys in a dictionary or members of a set.
- list()Builds a new list from anything you can loop over: the characters of a string, the numbers of a range, the keys of a dictionary, or another list.
- list comprehensionA list comprehension builds a new list from another collection in one readable line, with an optional filter to keep only some items.
- str.ljust()Returns a copy of a string padded on the right to the width you choose, so the text lines up on the left side.
- str.lower()Returns a copy of a string with every capital letter turned into a small (lower-case) letter. Useful for comparing text.
- str.lstrip()Removes whitespace, or any characters you list, from the start (left side) of a string. The right side stays as it is.
- map()Calls a function on every item of a list or other iterable and gives back the results, for example to turn a list of strings into numbers.
- match / casematch compares one value against a list of case patterns and runs the first that fits. It needs Python 3.10 or newer.
- max()Returns the largest item of a list or of several arguments, with a key function to choose what to compare and a default for empty data.
- min()Returns the smallest item of a list or of several arguments, with a key function to decide what smallest means and a default for empty data.
- next()Returns the next item from an iterator or generator. With a default value it returns that instead of raising StopIteration at the end.
- oct()Converts a whole number to an octal (base 8) string that starts with 0o, such as 0o755. Use int(text, 8) to convert back.
- open()Opens a file so you can read its text, write new text, or add lines to the end. Use it with a with block so the file closes itself.
- ord()Turns one character into its Unicode code point, the whole number that stands for it, such as 65 for A. chr() goes the other way.
- str.partition()Splits a string at the first match of a separator and returns a tuple of three: the part before, the separator, the part after.
- pass statementpass is a placeholder that does nothing. Use it where Python needs a statement but you have no code to write yet.
- list.pop()Removes an item from a list by position and gives it back to you. With no argument it takes the last item.
- dict.pop()Removes a key from a dictionary and returns its value. Give a default to avoid a KeyError when the key is missing.
- set.pop()Removes one element from a set and returns it. You cannot choose which: sets have no order, so treat it as arbitrary.
- dict.popitem()Removes the entry that was added last to a dictionary and returns it as a (key, value) pair. Raises KeyError when empty.
- pow()Raises a number to a power, like the operator, and with a third argument finds the remainder of that power quickly (modular power).
- print()Writes text, numbers and any other values to the screen, with control over the separator, the line ending and where the output goes.
- raise statementraise stops normal execution by throwing an exception, so bad input or impossible situations are reported instead of ignored.
- range()Produces a sequence of whole numbers from a start to an end, with an optional step, mostly used to repeat a for loop a set number of times.
- list.remove()Deletes the first item in a list that equals the value you give. Raises ValueError when no item matches.
- set.remove()Deletes an element from a set. Raises KeyError if the element is not in the set; use discard() to skip that check.
- str.removeprefix()Removes an exact piece of text from the start of a string, if the string begins with it. Otherwise the string comes back as it is.
- str.removesuffix()Removes an exact piece of text from the end of a string, if the string ends with it. Otherwise the string comes back as it is.
- str.replace()Returns a copy of a string where every match of one piece of text is swapped for another, or only the first few matches.
- repr()Returns a string that shows a value the way you would type it in code, with quotes and escape codes visible. Ideal for debugging.
- return statementreturn ends a function and sends a value back to the code that called it. Without a value, or without return, you get None.
- list.reverse()Turns a list around so the last item comes first. It changes the list itself and returns None; it does not sort.
- reversed()Gives the items of a list, string, range or dictionary in reverse order, one by one, without copying or changing the original.
- str.rjust()Returns a copy of a string padded on the left to the width you choose, so the text lines up on the right side.
- round()Rounds a number to the nearest whole number or to a chosen number of decimals, with two surprises: halves go to the even side and floats are not exact.
- str.rsplit()Cuts a string into a list of pieces like split(), but when you limit the cuts with maxsplit it starts from the right end.
- str.rstrip()Removes whitespace, or any characters you list, from the end (right side) of a string, such as the new line at the end of a line.
- set()Builds a set, a collection where every item appears only once: the quick way to remove duplicates and to find what two groups share.
- setattr()Sets an attribute on an object when the attribute name is in a string. It works like obj.name = value, but the name can come from data.
- dict.setdefault()Returns the value of a key. If the key is missing, it first adds it with the default value, then returns that default.
- slicing [start:stop:step]Slicing takes a part of a list, string or tuple with [start:stop:step]: the start is included, the stop is not, and step skips items.
- list.sort()Puts the items of a list in order, smallest first by default. It changes the list itself and returns None.
- sorted()Returns a new sorted list from any collection, smallest first or reversed, with a key function to sort by length, by a field or ignoring case.
- str.split()Cuts a string into a list of pieces: into words by default, or at any separator you choose, such as a comma.
- str.splitlines()Splits a text into a list of lines at every line break, whether it is written as \n, \r\n or \r, without an empty last line.
- str.startswith()Returns True when a string begins with the text you give, or with any one of several options passed as a tuple.
- str()Turns numbers, lists and any other value into readable text, so you can join it with other strings, print it or save it to a file.
- str.strip()Removes spaces, tabs and new lines from the start and end of a string, or any set of characters you list.
- sum()Adds up all the numbers in a list, tuple or any other iterable, with an optional starting value, in one short and fast call.
- super()Gives access to the parent class's methods from inside a child class, most often to run the parent's __init__ before adding your own setup.
- str.swapcase()Returns a copy of a string where capital letters become small and small letters become capitals. Other characters stay.
- set.symmetric_difference()Returns a new set with the elements that are in exactly one of the two sets, never in both. Same as the ^ operator.
- str.title()Returns a copy of a string with the first letter of every word in capitals and the other letters small, like a book title.
- try / except / else / finallytry runs code that might fail; except catches the error so your program can react, and else and finally add extra steps.
- tuple()Builds a tuple, an ordered sequence that cannot be changed after it is made, from a list, a string or anything else you can loop over.
- type()Tells you the type of any value, such as int, str, list or dict, which helps when a program does not behave the way you expect.
- set.union()Returns a new set with every element that is in this set or in any of the others, each one only once. Same as the | operator.
- dict.update()Adds the keys and values from another dictionary (or from pairs or keyword arguments), replacing values for keys already there.
- set.update()Adds every element from one or more lists, sets or other iterables into the set, in place. Duplicates are ignored.
- str.upper()Returns a copy of a string with every letter turned into a capital (upper-case) letter. Digits and symbols stay the same.
- dict.values()Returns a live view of all the values in a dictionary, in key order. Handy for totals, maximums and searching values.
- while loopA while loop repeats a block of code as long as its condition stays true, for when you do not know how many rounds you need.
- with statementwith sets something up, runs your block, then always cleans up, even after an error. It is the standard way to open files.
- yield (generators)yield turns a function into a generator that hands out values one at a time, pausing between them, instead of building a whole list.
- str.zfill()Adds zeros to the left of a string until it reaches the width you ask for, keeping a + or - sign at the front.
- zip()Pairs up items from two or more lists by position, so you can loop over them together, build a dictionary, or split pairs apart again.