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.

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

Spotted a mistake on this page? Tell us