Python function index
Search common Python built-ins, collection methods, and file operations.
Use the search to find a built-in function, method, or file operation by name or task. Expand an entry for a concise explanation and example. This quick reference focuses on the Python features used in the course; use the official documentation for full signatures and edge cases.
The examples assume Python 3. Where useful, the entry names distinguish a built-in function from a method on a list, string, or mapping.
Sources: Python built-in functions, Built-in types, Input and output, pathlib
21 results in 4 categories
Built-ins and conversion
Common functions available without importing a module.
printprint(*objects, sep=" ", end="\n")Write values to standard output.
Use print for quick output and debugging; production programs often use the logging module for diagnostics.
name = "Ari"
print("Hello", name) # Hello AriPython documentation inputinput(prompt="")Read one line of text from the user.
The result is always a string. Convert it explicitly before using it as a number.
age_text = input("Age: ")
age = int(age_text)Python documentation lenlen(object)Return the number of items in a collection.
Works with strings, lists, dictionaries, tuples, sets, and other sized objects.
colors = ["red", "blue"]
print(len(colors)) # 2Python documentation typetype(object)Return the object’s type.
Useful for inspection. Use isinstance when checking a type in application logic because it supports subclasses.
value = 42
print(type(value).__name__) # intPython documentation isinstanceisinstance(object, classinfo)Check whether a value has a given type.
The second argument can be a type or a tuple of types.
value = 42
print(isinstance(value, (int, float))) # TruePython documentation int / float / str / boolint(value) | float(value) | str(value) | bool(value)Convert a value to a built-in type.
Conversions can fail when input text is not a valid number. bool follows truth-value rules; non-empty strings such as "False" are true.
count = int("12")
ratio = float("0.5")
print(str(count), bool("")) # 12 FalsePython documentation list / tuple / set / dictlist(iterable) | tuple(iterable) | set(iterable) | dict(...)Create common built-in collection types.
Choose a list for an ordered mutable sequence, tuple for a fixed sequence, set for unique values, and dict for key-value mappings.
unique_ids = set([1, 1, 2])
lookup = dict(name="Ari", active=True)Python documentation Iteration and summaries
Loop over values and calculate common results.
rangerange(start, stop, step)Generate an integer sequence for iteration.
The stop value is excluded. range is a lazy range object, not a list.
for index in range(3):
print(index) # 0, 1, 2Python documentation enumerateenumerate(iterable, start=0)Pair each item with its index.
Prefer this to manually incrementing a counter in a loop.
for index, color in enumerate(["red", "blue"], start=1):
print(index, color)Python documentation zipzip(*iterables)Iterate over multiple sequences together.
By default, iteration stops at the shortest input. Use strict=True when unequal lengths should raise an error.
names = ["Ari", "Bea"]
scores = [90, 85]
for name, score in zip(names, scores):
print(name, score)Python documentation sortedsorted(iterable, key=None, reverse=False)Return a new sorted list from an iterable.
Use key to choose the value to sort by; sorted does not mutate the input.
words = ["pear", "fig", "apple"]
print(sorted(words, key=len)) # sorted by lengthPython documentation min / max / summin(iterable) | max(iterable) | sum(iterable)Find an extreme value or add numeric values.
min and max also accept multiple positional values. sum is for numeric totals, not string concatenation.
scores = [72, 91, 85]
print(min(scores), max(scores), sum(scores)) # 72 91 248Python documentation any / allany(iterable) | all(iterable)Check whether any or all values are truthy.
Both can short-circuit. For an empty iterable, any returns False and all returns True.
scores = [72, 91, 85]
print(all(score >= 60 for score in scores)) # TruePython documentation Collection and string methods
Use common methods to update and inspect built-in data.
list.append / list.extenditems.append(value) | items.extend(iterable)Add one item or multiple items to a list.
append adds its argument as a single element; extend iterates over the argument and adds each value.
items = [1, 2]
items.append([3, 4]) # [1, 2, [3, 4]]
items.extend([5, 6])Python documentation dict.get / dict.itemsmapping.get(key, default=None) | mapping.items()Read an optional key or iterate over key-value pairs.
get avoids a KeyError when a key is absent. items returns a view that reflects mapping changes.
user = {"name": "Ari"}
print(user.get("role", "member")) # member
for key, value in user.items():
print(key, value)Python documentation str.striptext.strip(chars=None)Remove leading and trailing whitespace or selected characters.
strip treats chars as a set of characters, not as a substring.
text = " hello "
print(text.strip()) # helloPython documentation str.splittext.split(sep=None, maxsplit=-1)Split a string into a list of parts.
With no separator, runs of whitespace are treated as one delimiter.
csv_line = "tea,coffee"
print(csv_line.split(",")) # two partsPython documentation str.joinseparator.join(iterable)Join strings with a separator between them.
Every item must be a string; convert values explicitly when needed.
parts = ["data", "science"]
print(" ".join(parts)) # data sciencePython documentation str.replacetext.replace(old, new, count=-1)Return a string with matching substrings replaced.
Strings are immutable, so replace returns a new string instead of changing the original.
label = "old title"
print(label.replace("old", "new")) # new titlePython documentation Files and paths
Open files safely and use paths for everyday file operations.
openopen(file, mode="r", encoding=None)Open a file and return a file object.
Use a with statement so the file is closed even when an error occurs. Specify an encoding for text files.
with open("notes.txt", encoding="utf-8") as file:
text = file.read()Python documentation Path.read_text / write_textpath.read_text(encoding=...) | path.write_text(text, encoding=...)Read or write an entire text file with pathlib.
Path methods are convenient for small text files. Stream large files with open instead.
from pathlib import Path
path = Path("notes.txt")
path.write_text("hello", encoding="utf-8")
text = path.read_text(encoding="utf-8")Python documentation Finished the course? Visit the references and further reading.