119 entries · 7 categories
Python reference
Keywords, built-in functions, string, list and dictionary methods, classes and objects, and the most used standard modules. Every example has a verified output and runs right in your browser.
119 entries
Syntax and keywords
Conditions, loops, functions, classes, exceptions and comprehensions.
- if, elif, elseA conditional statement that runs different code depending on conditions.
- forA loop that goes through the successive items of a sequence or other iterable object.
- whileA loop that repeats a block of code while a condition is true.
- break and continueBreaking out of a loop, or skipping to its next pass.
- defDefines a function: a named block of code with parameters that you can call multiple times.
- returnEnds a function and returns a value to the place it was called from.
- lambdaA short anonymous function written as a single expression.
- classDefines a class: a template for objects that combines data with the functions that act on it.
- try, except, else, finallyException handling: catching errors without stopping the program.
- raiseRaises an exception, signaling an error or a disallowed situation.
- withA context manager: automatic setup and cleanup of resources.
- importLoads a module, or selected names from a module, into the current file.
- passAn empty statement: a placeholder for code that does not do anything yet.
- match, casePattern matching: choosing a branch of code based on a value’s data and shape.
- List comprehensionsA concise way to build lists, sets, and dictionaries from other collections.
- f-stringsStrings with inserted expression values: f"You have {points} pts".
- global and nonlocalLet a function change variables from the global scope or from an enclosing function.
- yieldCreates a generator: a function that returns successive values on demand.
- async and awaitAsynchronous programming: waiting for operations without blocking the whole program.
- assertChecks an assumption in the code and raises AssertionError when it does not hold.
Built-in functions
Functions available without an import: print, len, range, sorted and more.
- print()Writes values to standard output, which is the console by default.
- input()Reads a line of text typed by the user in the console.
- len()Returns the number of items in a collection, or the number of characters in a string.
- range()Creates a sequence of integers, most often for a for loop.
- type()Returns the type of an object.
- isinstance()Checks whether an object is of a given type, or of a subtype of it.
- int()Converts a value to an integer.
- float()Converts a value to a floating-point number.
- str()Converts a value to a string.
- bool()Converts a value to True or False according to the rules of truthiness.
- list()Creates a list, either empty or from the items of another iterable.
- dict()Creates a dictionary from key-value pairs or keyword arguments.
- set()Creates a set: an unordered collection of unique items.
- tuple()Creates a tuple: an immutable sequence of items.
- enumerate()Adds a counter to items while looping over them.
- zip()Pairs up (or groups into tuples) the matching items of several collections.
- map()Calls a function for every item and returns an iterator of results.
- filter()Returns an iterator of items for which a function returns a truthy value.
- sorted()Returns a new, sorted list built from the items of any collection.
- reversed()Returns an iterator that walks through a sequence from the end.
- sum()Adds together all the numbers in a collection.
- min()Returns the smallest item in a collection, or the smallest of several arguments.
- max()Returns the largest item in a collection, or the largest of several arguments.
- abs()Returns the absolute value of a number.
- round()Rounds a number to the given number of decimal places.
- any()Checks whether at least one item in a collection is truthy.
- all()Checks whether every item in a collection is truthy.
- open()Opens a file for reading or writing and returns a file object.
- help()Displays the built-in documentation for an object, function, or module.
- dir()Returns a list of the names of an object’s attributes and methods.
- iter()Returns an iterator for a collection, an object that hands out its items one at a time. This is the mechanism behind the for loop.
- next()Fetches the next item from an iterator. Once it is exhausted, returns a default value or raises StopIteration.
- getattr()Reads an object’s attribute by a name given as a string, optionally with a default value.
- hasattr()Checks whether an object has an attribute or method with the given name. Returns True or False.
- chr()Returns the character for the given Unicode code point, e.g. chr(65) is "A". The opposite of ord().
- ord()Returns the Unicode code point of a single character, e.g. ord("A") is 65. The opposite of chr().
String methods
Changing case, splitting, joining, searching and formatting.
- str.upper()Returns a copy of the string written in uppercase letters.
- str.lower()Returns a copy of the string written in lowercase letters.
- str.strip()Removes whitespace (or given characters) from the start and end of a string.
- str.split()Splits a string into a list of parts using a separator.
- str.join()Joins the elements of a collection of strings into one string with a separator.
- str.replace()Returns a string with occurrences of a given fragment replaced.
- str.find()Returns the index of the first occurrence of a fragment, or -1.
- str.startswith()Checks whether a string starts with a given fragment.
- str.endswith()Checks whether a string ends with a given fragment.
- str.format()Inserts values into the places marked with curly braces.
- str.count()Counts non-overlapping occurrences of a fragment in a string.
- str.title()Returns a string in which every word starts with an uppercase letter.
- str.capitalize()Returns a string with the first letter uppercase and the rest lowercase.
- str.isdigit()Checks whether a string consists only of digits.
- str.zfill()Pads a string with zeros on the left up to a given length.
- str.splitlines()Splits a string into a list of lines.
- String slicing [start:stop:step]Getting fragments of a string by index.
Lists and tuples
Adding, removing, sorting and slicing items.
- list.append()Adds one item to the end of a list.
- list.extend()Adds all the items of another collection to the end of a list.
- list.insert()Inserts an item at a chosen position in a list.
- list.remove()Removes the first occurrence of a given value from a list.
- list.pop()Removes the item at the given index (the last one by default) and returns it.
- list.clear()Removes all the items from a list.
- list.index()Returns the index of the first occurrence of a value in a list.
- list.count()Counts how many times a value occurs in a list.
- list.sort()Sorts a list in place.
- list.reverse()Reverses the order of the items in a list in place.
- list.copy()Returns a shallow copy of a list.
- List slicing [start:stop:step]Getting, replacing, and deleting fragments of a list by index.
- Unpacking sequencesAssigning the items of a tuple or list to several variables at once.
Dictionaries and sets
Reading keys and values, updating dictionaries and set operations.
- dict.get()Returns the value for a key, or a default value when the key is not in the dictionary.
- dict.keys()Returns a view of the dictionary's keys that always reflects its current contents.
- dict.values()Returns a view of the dictionary values, ready for loops, sums, and lookups.
- dict.items()Returns a view of (key, value) pairs, the most convenient way to loop over a dictionary.
- dict.update()Adds pairs from another dictionary or from arguments to a dictionary, overwriting existing keys.
- dict.pop()Removes a key from a dictionary and returns its value, optionally with a fallback value.
- dict.setdefault()Returns the value of a key, and first stores a default value in the dictionary when the key is missing.
- Dict comprehensionsA concise way to build a new dictionary by transforming or filtering another collection.
- set.add()Adds an element to a set. If the element is already there, the set doesn't change.
- set.discard()Removes an element from a set if it's there. A missing element causes no error.
- set.union()Returns a new set with the elements from every given set, without duplicates.
- set.intersection()Returns a new set with the elements that appear in every given set.
- set.difference()Returns a new set with the elements of the first set that are not in the others.
Classes and objects
Constructors, inheritance, properties, special methods, decorators and data classes.
- __init__()A method called automatically when an object is created. It stores the object’s initial data, its attributes.
- selfThe first parameter of a method: the object the method was called on. It gives access to that object’s attributes and other methods.
- InheritanceBuilding one class on top of another: the derived class inherits the base class’s methods and can extend or override them.
- super()Calls a method of the base class from inside the derived class, most often the __init__ constructor.
- @propertyTurns a method into an attribute: the value is computed on read, and an optional setter controls writes.
- @staticmethodA method that gets neither the object nor the class automatically. It behaves like a plain function placed inside a class.
- @classmethodA method that receives the class (cls) instead of an object. It is most often used as an alternative constructor.
- __str__() and __repr__()Methods that define an object’s text appearance: readable for the user (__str__) and technical for the programmer (__repr__).
- Special methodsMethods with double underscores that let objects work with the ==, <, + and in operators, and with the len() function.
- @dataclassA decorator that generates __init__, __repr__, and __eq__ for a data-storing class, based on type-annotated fields.
- DecoratorsFunctions that wrap other functions and add behavior to them, such as logging or permission checks. Written as @name.
- *args and **kwargsCollecting any number of positional arguments into a tuple and keyword arguments into a dictionary, plus unpacking a collection at call time.
Comparisons
How similar types, functions and methods differ and when to pick each one.
- list vs tuplelist is a mutable sequence you can modify, while tuple is an immutable sequence that can be a dictionary key or a set element.
- append() vs extend()append() adds exactly one element to the end of a list, even if that element is itself a list, while extend() appends every element of the given collection in turn.
- sort() vs sorted()list.sort() sorts the list in place and returns None, while sorted() returns a new, sorted list from any collection and leaves the original untouched.
- @staticmethod vs @classmethod@staticmethod behaves like a plain function with no automatic argument, while @classmethod receives the class as cls and usually serves as an alternative constructor.
- namedtuple vs dataclassnamedtuple creates an immutable, lightweight tuple with named fields, while @dataclass creates an ordinary, mutable class with a generated __init__, __repr__, and __eq__.
- os vs pathlibos represents paths as plain strings and operates on them with functions, while pathlib represents a path as a Path object with methods and the / operator.
- lambda vs deflambda creates a short, anonymous function with one expression, while def defines a named function that can have multiple statements, default values, and a docstring.
- map() vs list comprehensionmap() calls a function for every element and returns a lazy iterator, while a list comprehension builds a new list right away and can filter with an if condition.