| Function/Method | Belongs To | Description |
|---|---|---|
abs() | Built-in | Returns the absolute (positive) value of a number. For example, abs(-7) returns 7 and abs(3.5) returns 3.5. Useful when you only care about magnitude, not direction. |
all() | Built-in | Returns True if every item in an iterable is truthy (or if the iterable is empty). For example, all([True, 1, 'yes']) returns True, but all([True, 0]) returns False because 0 is falsy. Introduced in: |
any() | Built-in | Returns True if at least one item in an iterable is truthy. For example, any([False, 0, 5]) returns True because 5 is truthy. Introduced in: |
ascii() | Built-in | Returns a string representation of an object where non-ASCII characters are escaped. For example, ascii("cafe") returns a quoted string with any accented characters replaced by their escape sequences. |
bin() | Built-in | Converts an integer to its binary string prefixed with 0b. For example, bin(10) returns '0b1010', and bin(255) returns '0b11111111'. |
bool() | Built-in | Converts a value to a Boolean. For example, bool(0) returns False, bool("hello") returns True, and bool([]) returns False (empty list). Almost all Python values are truthy except 0, "", [], None. Introduced in: |
bytearray() | Built-in | Creates a mutable sequence of bytes. For example, bytearray(5) creates 5 zero bytes, and bytearray(b"hello") creates one from a bytes literal. Unlike bytes, a bytearray can be modified in place. |
bytes() | Built-in | Creates an immutable sequence of bytes. For example, bytes(5) creates 5 zero bytes, and bytes("hello", "utf-8") encodes the string as bytes. Used for binary data, networking, and file I/O. |
callable() | Built-in | Returns True if the object can be called like a function. For example, callable(print) returns True, and callable(42) returns False. Introduced in: |
chr() | Built-in | Returns the string character for a given Unicode code point. For example, chr(65) returns 'A', and chr(9829) returns a heart symbol. The inverse of ord(). |
compile() | Built-in | Compiles source code (a string) into a code object that can be executed by exec() or eval(). For example, compile("1+2", " creates a compiled expression. |
complex() | Built-in | Creates a complex number. For example, complex(3, 4) returns (3+4j). Python uses j (not i) for the imaginary unit. |
delattr() | Built-in | Deletes an attribute from an object. For example, delattr(obj, "name") removes the name attribute. Equivalent to del obj.name but useful when the attribute name is a variable. Introduced in: |
dict() | Built-in | Creates a new dictionary. For example, dict(name="Alice", age=20) returns {"name": "Alice", "age": 20}. Introduced in: |
dir() | Built-in | Returns a list of all attributes and methods of an object. For example, dir("hello") shows all string methods. Handy for exploring an unfamiliar object or module. Introduced in: |
divmod() | Built-in | Returns a tuple of (quotient, remainder) from integer division. For example, divmod(17, 5) returns (3, 2) because 17 ÷ 5 = 3 remainder 2. Introduced in: |
enumerate() | Built-in | Wraps an iterable and yields (index, value) pairs. For example, for i, item in enumerate(["a","b","c"]) gives 0,'a', 1,'b', 2,'c'. Introduced in: |
eval() | Built-in | Evaluates a string as a Python expression and returns the result. For example, eval("2 + 2") returns 4. Use with caution — never evaluate untrusted input. |
exec() | Built-in | Executes a string or compiled code object as Python statements. Unlike eval() which returns a value, exec() runs multi-line code. For example, exec("x = 5\nprint(x)") defines and prints x. |
filter() | Built-in | Filters elements of an iterable using a function, keeping only those where the function returns True. For example, list(filter(lambda x: x > 0, [-1, 2, -3, 4])) returns [2, 4]. Introduced in: |
float() | Built-in | Converts a value to a floating-point number. For example, float("3.14") returns 3.14 and float(5) returns 5.0. Introduced in: |
format() | Built-in | Formats a value using a format spec. For example, format(3.14159, ".2f") returns '3.14', and format(255, "x") returns 'ff' (hexadecimal). Introduced in: |
frozenset() | Built-in | Creates an immutable set that cannot be modified. For example, frozenset([1, 2, 3]) can be used as a dictionary key, unlike a regular mutable set. Introduced in: |
getattr() | Built-in | Returns the value of an attribute using its name as a string. For example, getattr(obj, "name") is equivalent to obj.name. You can provide a default: getattr(obj, "missing", "default") won't raise an error. Introduced in: |
globals() | Built-in | Returns the current global symbol table as a dictionary. For example, print(globals()) shows all variables defined at module level. Introduced in: |
hasattr() | Built-in | Returns True if an object has the given attribute. For example, hasattr(obj, "name") checks whether the attribute exists without raising an AttributeError. Introduced in: |
hash() | Built-in | Returns the integer hash of an object, used internally by dicts and sets. Only immutable (hashable) objects like strings, numbers, and tuples can be hashed. |
help() | Built-in | Prints built-in help documentation. For example, help(str) shows all string methods. Running help() starts an interactive help session. |
hex() | Built-in | Converts an integer to a lowercase hex string prefixed with 0x. For example, hex(255) returns '0xff'. |
id() | Built-in | Returns the unique memory address (as an integer) of an object. Useful for checking whether two variables reference the exact same object in memory. |
input() | Built-in | Pauses execution and reads a line of text from the user. For example, name = input("Enter your name: ") stores whatever the user types. The value is always a string. Introduced in: |
int() | Built-in | Converts a value to an integer. For example, int("42") returns 42, and int(3.9) returns 3 (truncates toward zero). Introduced in: |
isinstance() | Built-in | Returns True if an object is an instance of the given class or type. For example, isinstance(42, int) returns True. Safer than comparing type() directly. Introduced in: |
issubclass() | Built-in | Returns True if a class is a subclass of another. For example, issubclass(bool, int) returns True because bool inherits from int. Introduced in: |
iter() | Built-in | Returns an iterator object from an iterable. For example, it = iter([1, 2, 3]) creates an iterator you can step through with next(). Introduced in: |
len() | Built-in | Returns the number of items in an object. For example, len([1, 2, 3]) returns 3, and len("hello") returns 5. Works on strings, lists, tuples, dicts, sets, and more. Introduced in: |
list() | Built-in | Creates a list from an iterable. For example, list((1, 2, 3)) converts a tuple to a list, and list("abc") gives ["a","b","c"]. Introduced in: |
locals() | Built-in | Returns a dictionary of the current local symbol table. Inside a function, print(locals()) shows all local variables. Introduced in: |
map() | Built-in | Applies a function to every item in an iterable and returns a lazy iterator. For example, list(map(str, [1, 2, 3])) returns ["1","2","3"]. Introduced in: |
max() | Built-in | Returns the largest item. For example, max([3, 1, 4, 1, 5]) returns 5. You can pass a key function for custom comparison. Introduced in: |
min() | Built-in | Returns the smallest item. For example, min([3, 1, 4]) returns 1. |
next() | Built-in | Returns the next item from an iterator. For example, it = iter([10,20,30]); next(it) returns 10. Provide a default to avoid StopIteration: next(it, None). Introduced in: |
object() | Built-in | Returns a new featureless base object. Rarely used directly, but object is the root class all Python classes inherit from. |
oct() | Built-in | Converts an integer to its octal string prefixed with 0o. For example, oct(8) returns '0o10'. |
open() | Built-in | Opens a file and returns a file object. For example, open("data.txt", "r") opens a file for reading. Always use with a with statement for automatic cleanup. Introduced in: |
ord() | Built-in | Returns the Unicode code point for a single character. For example, ord("A") returns 65. The inverse of chr(). |
pow() | Built-in | Returns x raised to the power y. For example, pow(2, 10) returns 1024, and pow(2, 10, 1000) returns 24 (result modulo 1000). Introduced in: |
print() | Built-in | Outputs text or values to the console. For example, print("Hello") displays Hello. Supports sep= (separator), end= (line ending), and file= (output target). Introduced in: |
property() | Built-in | Creates a property descriptor, allowing getter, setter, and deleter methods. Use the @property decorator above a method to expose it as an attribute-style accessor. Introduced in: |
range() | Built-in | Generates a sequence of integers. For example, range(5) produces 0–4, range(1,6) produces 1–5, and range(0,10,2) counts in steps of 2. Introduced in: |
repr() | Built-in | Returns a developer-friendly string representation of an object. For example, repr("hello\n") shows the escaped newline character. Aims to produce a string that could recreate the object. |
reversed() | Built-in | Returns an iterator that steps through a sequence in reverse. For example, list(reversed([1,2,3])) returns [3,2,1]. |
round() | Built-in | Rounds a number to a given number of decimal places. For example, round(3.14159, 2) returns 3.14. With no second argument it returns an integer. Introduced in: |
set() | Built-in | Creates a set — an unordered collection of unique elements. For example, set([1, 2, 2, 3]) returns {1, 2, 3} (duplicates removed). Introduced in: |
setattr() | Built-in | Sets an attribute on an object using its name as a string. For example, setattr(obj, "score", 100) is equivalent to obj.score = 100. Introduced in: |
slice() | Built-in | Creates a slice object representing a range of indices. For example, s = slice(1, 4) can be used to index a list: ["a","b","c","d","e"][s] returns ["b","c","d"]. |
sorted() | Built-in | Returns a new sorted list from any iterable. For example, sorted([3,1,4,1,5]) returns [1,1,3,4,5], and sorted(words, key=len) sorts strings by length. Introduced in: |
staticmethod() | Built-in | Marks a method as static — it receives no implicit first argument. Use @staticmethod to define a utility function that belongs to the class namespace but needs no instance. Introduced in: |
str() | Built-in | Converts a value to a string. For example, str(42) returns '42', and str(None) returns 'None'. Introduced in: |
sum() | Built-in | Returns the sum of all items in an iterable. For example, sum([1,2,3,4]) returns 10, and sum([1,2,3], 10) starts from 10 giving 16. Introduced in: |
super() | Built-in | Returns a proxy object referring to the parent class. Typically used in __init__() as super().__init__() to call the parent initializer without naming it explicitly. Introduced in: |
tuple() | Built-in | Creates a tuple from an iterable. For example, tuple([1,2,3]) returns (1,2,3). Tuples are immutable — their values cannot be changed after creation. Introduced in: |
type() | Built-in | Returns the type (class) of an object. For example, type(42) returns , and type("hello") returns . Introduced in: |
vars() | Built-in | Returns the __dict__ attribute — a dictionary of an object's writable attributes. Called without arguments it behaves like locals(). |
zip() | Built-in | Combines two or more iterables element-by-element into tuples. For example, list(zip([1,2],["a","b"])) returns [(1,"a"),(2,"b")]. Stops at the shortest iterable. Introduced in: |
capitalize() | String | Returns a copy with the first character uppercased and the rest lowercased. For example, "hello world".capitalize() returns 'Hello world'. |
casefold() | String | Returns a lowercase version designed for case-insensitive comparisons. More aggressive than lower() — for example, the German character 'ss' is handled properly. |
center() | String | Returns the string centered in a field of given width, padded with a fill character. For example, "hi".center(10) returns ' hi '. |
count() | String | Returns the number of non-overlapping occurrences of a substring. For example, "banana".count("an") returns 2. Introduced in: |
encode() | String | Encodes the string to bytes using the given encoding (default UTF-8). For example, "hello".encode() returns b"hello". Used when working with binary files or network data. |
endswith() | String | Returns True if the string ends with the specified suffix. For example, "report.pdf".endswith(".pdf") returns True. Accepts a tuple of suffixes. |
expandtabs() | String | Replaces tab characters with spaces to align to tab stops. For example, "a\tb".expandtabs(4) returns 'a b'. |
find() | String | Returns the lowest index where a substring is found, or -1 if not found. For example, "hello".find("ll") returns 2. Doesn't raise an error when missing, unlike index(). Introduced in: |
format() | String | Formats the string by replacing {} placeholders with values. For example, "Hello, {}!".format("Alice") returns 'Hello, Alice!'. Introduced in: |
format_map() | String | Like format() but uses a dictionary for substitutions. For example, "{name}".format_map({"name": "Alice"}) returns 'Alice'. |
index() | String | Returns the lowest index where a substring is found. Raises ValueError if not found. For example, "hello".index("e") returns 1. Use find() to avoid errors. |
isalnum() | String | Returns True if all characters are alphanumeric and the string is non-empty. For example, "abc123".isalnum() is True, but "abc 123".isalnum() is False (space is not alphanumeric). |
isalpha() | String | Returns True if all characters are alphabetic and the string is non-empty. For example, "hello".isalpha() is True. |
isascii() | String | Returns True if all characters are ASCII. For example, "hello".isascii() is True, but a string containing accented characters returns False. |
isdecimal() | String | Returns True if all characters are decimal digits (0–9). Stricter than isdigit() — does not accept superscripts. For example, "123".isdecimal() is True. |
isdigit() | String | Returns True if all characters are digit characters. Slightly broader than isdecimal() — includes some Unicode superscripts. For example, "9".isdigit() is True. |
isidentifier() | String | Returns True if the string is a valid Python identifier. For example, "my_var".isidentifier() is True, but "123abc".isidentifier() is False. |
islower() | String | Returns True if all cased characters are lowercase. For example, "hello".islower() is True, and "Hello".islower() is False. |
isnumeric() | String | Returns True if all characters are numeric, including Unicode numerals like fractions. Broader than isdigit(). |
isprintable() | String | Returns True if all characters are printable (visible or space). For example, "hello\n".isprintable() is False due to the newline. |
isspace() | String | Returns True if the string contains only whitespace. For example, " ".isspace() is True. |
istitle() | String | Returns True if the string is titlecased — each word starts with a capital. For example, "Hello World".istitle() is True. |
isupper() | String | Returns True if all cased characters are uppercase. For example, "HELLO".isupper() is True. |
join() | String | Joins elements of an iterable into a single string with the string as separator. For example, ", ".join(["a","b","c"]) returns 'a, b, c'. |
ljust() | String | Returns the string left-justified in a field of given width. For example, "hi".ljust(10, "-") returns 'hi--------'. |
lower() | String | Returns the string with all characters converted to lowercase. For example, "Hello World".lower() returns 'hello world'. |
lstrip() | String | Returns the string with leading whitespace (or characters) removed. For example, " hello".lstrip() returns 'hello'. |
maketrans() | String | Creates a translation table for translate(). For example, str.maketrans("abc","xyz") maps a→x, b→y, c→z. |
partition() | String | Splits at the first occurrence of a separator, returning (before, sep, after). For example, "hello:world".partition(":") returns ("hello",":", "world"). |
replace() | String | Returns a new string with all occurrences of a substring replaced. For example, "hello world".replace("world","Python") returns 'hello Python'. Introduced in: |
rfind() | String | Like find() but searches from the right. For example, "banana".rfind("a") returns 5 (the last 'a'). |
rindex() | String | Like index() but searches from the right. Raises ValueError if not found. |
rjust() | String | Returns the string right-justified in a field of given width. For example, "hi".rjust(10,"0") returns '00000000hi'. |
rpartition() | String | Like partition() but splits at the last occurrence. For example, "a:b:c".rpartition(":") returns ("a:b",":","c"). |
rsplit() | String | Splits from the right. For example, "a,b,c".rsplit(",", 1) returns ["a,b","c"] — splitting once from the right. |
rstrip() | String | Returns the string with trailing whitespace removed. For example, "hello ".rstrip() returns 'hello'. |
split() | String | Splits the string at the separator and returns a list. For example, "hello world".split() returns ["hello","world"]. Introduced in: |
splitlines() | String | Splits at line boundaries. For example, "line1\nline2".splitlines() returns ["line1","line2"]. |
startswith() | String | Returns True if the string starts with the prefix. For example, "https://efiwe.com".startswith("https") returns True. |
strip() | String | Returns the string with leading and trailing whitespace removed. For example, " hello ".strip() returns 'hello'. |
swapcase() | String | Swaps uppercase to lowercase and vice versa. For example, "Hello World".swapcase() returns 'hELLO wORLD'. |
title() | String | Returns a titlecased string where each word starts with uppercase. For example, "hello world".title() returns 'Hello World'. |
translate() | String | Translates characters using a table created by maketrans(). For example, using a table that maps 'a' to 'x', "banana".translate(table) replaces all 'a' characters. |
upper() | String | Returns the string with all characters converted to uppercase. For example, "hello".upper() returns 'HELLO'. |
zfill() | String | Pads the string on the left with zeros to reach the given width. For example, "42".zfill(5) returns '00042'. |
append() | List | Adds a single element to the end of the list. For example, nums = [1,2]; nums.append(3) makes nums become [1,2,3]. Introduced in: |
clear() | List | Removes all elements from the list. For example, my_list.clear() results in []. The list object still exists. |
copy() | List | Returns a shallow copy. For example, new = original.copy() creates a new list so modifying new doesn't affect original. |
count() | List | Returns the number of times a value appears. For example, [1,2,2,3,2].count(2) returns 3. |
extend() | List | Adds all elements of an iterable to the end. For example, [1,2].extend([3,4]) gives [1,2,3,4]. Unlike append(), it unpacks the iterable. Introduced in: |
index() | List | Returns the index of the first occurrence of a value. For example, [10,20,30].index(20) returns 1. Raises ValueError if not present. |
insert() | List | Inserts an element at a specified position. For example, nums = [1,3]; nums.insert(1, 2) gives [1,2,3]. Introduced in: |
pop() | List | Removes and returns the element at a given index (default: last). For example, nums = [1,2,3]; nums.pop() returns 3 and leaves [1,2]. Introduced in: |
remove() | List | Removes the first occurrence of a value. For example, [1,2,2,3].remove(2) gives [1,2,3]. Raises ValueError if not found. Introduced in: |
reverse() | List | Reverses the list in place. For example, nums = [1,2,3]; nums.reverse() makes nums become [3,2,1]. |
sort() | List | Sorts the list in place. For example, [3,1,4].sort() gives [1,3,4]. Use sort(reverse=True) for descending and sort(key=len) for a custom key. Introduced in: |
clear() | Dictionary | Removes all items from the dictionary. For example, d = {"a":1}; d.clear() makes d become {}. Introduced in: |
copy() | Dictionary | Returns a shallow copy. For example, new_d = d.copy() creates a new dict, so modifying new_d doesn't affect d. |
fromkeys() | Dictionary | Creates a dict from a sequence of keys, all set to the same value. For example, dict.fromkeys(["a","b","c"], 0) returns {"a":0,"b":0,"c":0}. |
get() | Dictionary | Returns the value for a key, or a default if the key is missing. For example, d.get("score", 0) returns the score or 0 — avoiding a KeyError. Introduced in: |
items() | Dictionary | Returns a view of all key-value pairs as tuples. For example, for k, v in d.items() lets you loop over both key and value at once. Introduced in: |
keys() | Dictionary | Returns a view of all keys. For example, list(d.keys()) gives all keys as a list. Introduced in: |
pop() | Dictionary | Removes and returns the value for the specified key. For example, d.pop("age") removes and returns the age. Provide a default to avoid KeyError: d.pop("age", None). Introduced in: |
popitem() | Dictionary | Removes and returns the last inserted key-value pair as a tuple. In Python 3.7+, dicts maintain insertion order, so this is deterministic. Introduced in: |
setdefault() | Dictionary | Returns the value for a key if it exists; otherwise inserts it with the given default. For example, d.setdefault("score", 0) sets score to 0 only if not already present. |
update() | Dictionary | Updates the dictionary with pairs from another dict. For example, d.update({"age": 21}) adds or overwrites the age key. Introduced in: |
values() | Dictionary | Returns a view of all values. For example, list(d.values()) gives all values as a list. The view reflects live changes. Introduced in: |
count() | Tuple | Returns the number of times a value appears in the tuple. For example, (1,2,2,3).count(2) returns 2. |
index() | Tuple | Returns the index of the first occurrence of a value. For example, ("a","b","c").index("b") returns 1. Raises ValueError if not found. |
add() | Set | Adds an element to the set. For example, s = {1,2}; s.add(3) makes s become {1,2,3}. Introduced in: |
clear() | Set | Removes all elements from the set. For example, s.clear() results in set(). |
copy() | Set | Returns a shallow copy of the set. |
difference() | Set | Returns elements in this set but not in others. For example, {1,2,3}.difference({2,3,4}) returns {1}. Also: {1,2,3} - {2,3,4}. |
difference_update() | Set | Removes all elements found in other sets from this set. For example, s.difference_update({2,3}) is like s -= {2,3}. |
discard() | Set | Removes an element if present — does not raise an error if missing. For example, s.discard(99) silently does nothing if 99 isn't there. |
intersection() | Set | Returns elements common to all given sets. For example, {1,2,3}.intersection({2,3,4}) returns {2,3}. Also: {1,2,3} & {2,3,4}. |
intersection_update() | Set | Keeps only elements also in other sets. For example, s.intersection_update({2,3}) is like s &= {2,3}. |
isdisjoint() | Set | Returns True if the two sets have no common elements. For example, {1,2}.isdisjoint({3,4}) is True. |
issubset() | Set | Returns True if all elements of this set are in another. For example, {1,2}.issubset({1,2,3}) is True. Also: {1,2} <= {1,2,3}. |
issuperset() | Set | Returns True if all elements of another set are in this set. For example, {1,2,3}.issuperset({1,2}) is True. Also: {1,2,3} >= {1,2}. |
pop() | Set | Removes and returns an arbitrary element. Since sets are unordered, you can't control which one is removed. |
remove() | Set | Removes a specific element. Raises KeyError if not found — use discard() to avoid that. Introduced in: |
symmetric_difference() | Set | Returns elements in either set but not both. For example, {1,2,3}.symmetric_difference({2,3,4}) returns {1,4}. Also: {1,2,3} ^ {2,3,4}. |
symmetric_difference_update() | Set | Updates the set to keep only elements not in both. For example, s.symmetric_difference_update({2,3}) is like s ^= {2,3}. |
union() | Set | Returns all elements from this set and others. For example, {1,2}.union({2,3,4}) returns {1,2,3,4}. Also: {1,2} | {3,4}. |
update() | Set | Adds all elements from an iterable to the set. For example, s.update([4,5]) adds 4 and 5 to s. |
close() | File | Closes the file and releases resources. Best practice is to use with open() as f which closes automatically. Introduced in: |
detach() | File | Separates the raw binary stream from the text wrapper and returns it. After calling this, the file object becomes unusable. |
fileno() | File | Returns the integer file descriptor used by the OS. Rarely needed in normal code; used for passing to OS-level calls. |
flush() | File | Forces any buffered data to be written to the file immediately without closing it. Useful for real-time log output. |
isatty() | File | Returns True if the file stream is connected to a terminal. |
read() | File | Reads and returns the entire file content (or up to n bytes). For example, content = f.read() stores the whole file as a string. Introduced in: |
readable() | File | Returns True if the file can be read. Files opened in write-only mode return False. |
readline() | File | Reads one line from the file (up to and including the newline). Calling it repeatedly steps through the file line by line. Introduced in: |
readlines() | File | Reads all lines and returns them as a list of strings. Consider for line in f for memory-efficient reading. Introduced in: |
seek() | File | Moves the read/write position to a given byte offset. For example, f.seek(0) rewinds to the start of the file. |
seekable() | File | Returns True if the file supports seek() and tell(). Network streams are typically not seekable. |
tell() | File | Returns the current file position as a byte offset from the start. |
truncate() | File | Resizes the file to the specified size in bytes. Any data beyond the new size is deleted. |
writable() | File | Returns True if the file can be written to. Files in read-only mode return False. |
write() | File | Writes a string to the file and returns the number of characters written. The file must be opened in write or append mode. Introduced in: |
writelines() | File | Writes a list of strings to the file. No newlines are added automatically — include \n in each string if needed. |
and | Keyword | A logical operator that returns True only if both conditions are true. For example, x > 0 and x < 10 is true only when x is between 1 and 9. Short-circuits: if the left side is false, the right is not evaluated. Introduced in: |
as | Keyword | Creates an alias. For example, import numpy as np lets you use np, and with open('f.txt') as f names the file object f. Introduced in: |
assert | Keyword | Tests a condition and raises AssertionError if false. For example, assert age >= 0, "Age cannot be negative" validates input. Assertions can be disabled with -O. Introduced in: |
async | Keyword | Defines an asynchronous function (a coroutine). For example, async def fetch_data(): creates a function that can pause while waiting for I/O, allowing other code to run. |
await | Keyword | Pauses execution inside an async function until the awaited coroutine completes. For example, result = await some_coroutine() yields control back to the event loop while waiting. |
break | Keyword | Immediately exits the nearest enclosing loop. For example, if score == 100: break stops iteration as soon as a perfect score is found. Introduced in: |
case | Keyword | Defines a pattern branch in a match statement. For example, case "admin": handles the value 'admin', and case _: is the default fallback. Introduced in: |
class | Keyword | Defines a new class. For example, class Learner: starts a class definition. Everything indented below belongs to the class. Introduced in: |
continue | Keyword | Skips the rest of the current loop iteration and moves to the next one. For example, if score < 0: continue skips invalid values without breaking the loop. Introduced in: |
def | Keyword | Defines a new function. For example, def greet(name): creates a function. Everything indented below is the function body. Introduced in: |
del | Keyword | Deletes a variable, list item, or attribute. For example, del my_list[2] removes item at index 2, and del my_var removes a variable entirely. Introduced in: |
elif | Keyword | Adds an additional condition to an if statement (short for 'else if'). For example, elif score >= 70: print('Pass') is checked only if the preceding if was false. Introduced in: |
else | Keyword | Runs when all preceding if/elif conditions are false. Also used with loops (runs when no break occurred) and with try (runs when no exception occurred). Introduced in: |
except | Keyword | Catches an exception raised inside a try block. For example, except ValueError as e: catches a ValueError. Multiple except blocks can handle different types. Introduced in: |
False | Keyword | The boolean literal for false. For example, is_active = False. False equals 0 numerically in Python. Introduced in: |
finally | Keyword | Runs a block whether or not an exception occurred in try. For example, finally: f.close() ensures the file is always closed. Introduced in: |
for | Keyword | Creates a loop that iterates over each item in an iterable. For example, for item in my_list: runs the body once per element. |
from | Keyword | Imports specific names from a module. For example, from math import sqrt imports only sqrt so you can call it without the math. prefix. Introduced in: |
global | Keyword | Declares that a variable inside a function refers to the module-level global. For example, global counter lets a function modify the outer counter variable. Introduced in: |
if | Keyword | Executes a block only when a condition is true. For example, if score >= 50: print('Pass') prints only when the threshold is met. Introduced in: |
import | Keyword | Loads a module into the current namespace. For example, import math gives access to math.sqrt() and other math functions. Introduced in: |
in | Keyword | Tests membership in a sequence. For example, "python" in skills returns True if the string is in the list. Also used in for loops. Introduced in: |
is | Keyword | Tests object identity — whether two variables point to the exact same object. For example, x is None is the recommended way to check for None. Introduced in: |
lambda | Keyword | Creates an anonymous function in a single expression. For example, square = lambda x: x ** 2 creates a function that squares its input. Introduced in: |
match | Keyword | Starts structural pattern-matching (Python 3.10+). For example, match command: case "quit": ... compares against each case. Introduced in: |
None | Keyword | Represents the absence of a value. A function with no return returns None by default. Use is None to check for it. Introduced in: |
nonlocal | Keyword | Declares that a variable in a nested function refers to the enclosing function's scope. For example, nonlocal count lets an inner function modify count in the outer function. Introduced in: |
not | Keyword | Logical NOT — inverts a boolean. For example, not True is False. Introduced in: |
or | Keyword | Returns True if at least one condition is true. For example, x < 0 or x > 100 catches out-of-range values. Introduced in: |
pass | Keyword | A no-op placeholder that does nothing. Used when a code block is required but you have nothing to put there yet. Introduced in: |
raise | Keyword | Raises an exception manually. For example, raise ValueError("Score must be positive") signals an error from your own code. Introduced in: |
return | Keyword | Exits a function and optionally sends back a value. A bare return or no return statement returns None. Introduced in: |
True | Keyword | The boolean literal for true. True equals 1 numerically in Python. Introduced in: |
try | Keyword | Starts a block where exceptions are caught. Code inside is monitored; any exception triggers the matching except handler instead of crashing. Introduced in: |
while | Keyword | Creates a loop that repeats as long as a condition is true. Always ensure the condition eventually becomes false to avoid infinite loops. Introduced in: |
with | Keyword | Manages a resource using a context manager, ensuring cleanup happens automatically. For example, with open("data.txt") as f: guarantees the file is closed. Introduced in: |
yield | Keyword | Pauses a generator function and returns a value to the caller without losing state. The function resumes on the next next() call. Introduced in: |
ArithmeticError | Exception | Base class for numeric calculation errors including ZeroDivisionError and OverflowError. |
AssertionError | Exception | Raised when an assert statement fails. For example, assert 1 == 2 raises AssertionError. |
AttributeError | Exception | Raised when you access or set an attribute that doesn't exist. For example, "hello".nonexistent raises AttributeError. |
EOFError | Exception | Raised when input() hits end-of-file with no data to read. |
FloatingPointError | Exception | Raised when a floating-point operation fails. Rarely seen — most floating-point errors produce inf or nan instead. |
GeneratorExit | Exception | Raised inside a generator when .close() is called on it, signalling the generator to stop. |
ImportError | Exception | Raised when an import cannot find or load a module. For example, import nonexistent_module raises this. |
IndentationError | Exception | Raised when indentation is incorrect. For example, mixing tabs and spaces in the same block causes this. |
IndexError | Exception | Raised when a sequence index is out of range. For example, [1,2,3][10] raises IndexError: list index out of range. Introduced in: |
KeyError | Exception | Raised when a dictionary key doesn't exist. For example, d = {"a":1}; d["b"] raises KeyError: "b". Use .get() to avoid it. Introduced in: |
KeyboardInterrupt | Exception | Raised when the user presses Ctrl+C to stop a running program. |
LookupError | Exception | Base class for IndexError and KeyError — raised when a lookup by key or index fails. |
MemoryError | Exception | Raised when a program runs out of memory. |
NameError | Exception | Raised when a variable is used before being defined. For example, print(undefined_var) raises NameError. |
NotImplementedError | Exception | Raised in abstract base classes to signal that a subclass must override a method. |
OSError | Exception | Raised when an OS-related operation fails — file not found, permission denied, etc. |
OverflowError | Exception | Raised when a numeric result is too large for the type to represent. |
RecursionError | Exception | Raised when the maximum recursion depth is exceeded. A function calling itself without a base case will trigger this. |
RuntimeError | Exception | A catch-all for unexpected runtime problems that don't fit another category. |
StopIteration | Exception | Raised by next() when an iterator has no more items. Used internally by for loops. Introduced in: |
SyntaxError | Exception | Raised when Python's parser encounters invalid syntax. Occurs before the program runs. |
TabError | Exception | Raised when indentation mixes tabs and spaces inconsistently (a subclass of IndentationError). |
TypeError | Exception | Raised when an operation is applied to the wrong type. For example, "hello" + 5 raises TypeError. |
UnboundLocalError | Exception | Raised when a local variable is referenced before being assigned inside a function. |
ValueError | Exception | Raised when a function receives the right type but a value that makes no sense. For example, int("abc") raises ValueError. Introduced in: |
ZeroDivisionError | Exception | Raised when dividing by zero. For example, 10 / 0 raises ZeroDivisionError: division by zero. Introduced in: |
math.acos() | Module | Returns the arc cosine of a number in radians. Input must be in [-1, 1]. For example, math.acos(1) returns 0.0. |
math.asin() | Module | Returns the arc sine of a number in radians. For example, math.asin(0) returns 0.0. |
math.atan() | Module | Returns the arc tangent of a number in radians. For example, math.atan(1) returns approximately 0.785 (π/4). |
math.atan2() | Module | Returns the arc tangent of y/x across all four quadrants. For example, math.atan2(1, 1) returns π/4. |
math.ceil() | Module | Rounds a number up to the nearest integer. For example, math.ceil(3.1) returns 4. |
math.cos() | Module | Returns the cosine of an angle in radians. For example, math.cos(0) returns 1.0. |
math.degrees() | Module | Converts radians to degrees. For example, math.degrees(math.pi) returns 180.0. |
math.exp() | Module | Returns e raised to the given power. For example, math.exp(1) returns approximately 2.718. |
math.fabs() | Module | Returns the absolute value as a float. For example, math.fabs(-5) returns 5.0. |
math.factorial() | Module | Returns the factorial of an integer. For example, math.factorial(5) returns 120 (5 × 4 × 3 × 2 × 1). |
math.floor() | Module | Rounds a number down to the nearest integer. For example, math.floor(3.9) returns 3. |
math.gcd() | Module | Returns the greatest common divisor of two integers. For example, math.gcd(12, 8) returns 4. |
math.hypot() | Module | Returns the Euclidean distance. For example, math.hypot(3, 4) returns 5.0 — the hypotenuse of a 3-4-5 triangle. |
math.log() | Module | Returns the natural logarithm (or log to any base). For example, math.log(math.e) returns 1.0, and math.log(100, 10) returns 2.0. |
math.log10() | Module | Returns the base-10 logarithm. For example, math.log10(1000) returns 3.0. |
math.log2() | Module | Returns the base-2 logarithm. For example, math.log2(8) returns 3.0. |
math.pow() | Module | Returns x raised to y as a float. For example, math.pow(2, 10) returns 1024.0. Introduced in: |
math.radians() | Module | Converts degrees to radians. For example, math.radians(180) returns approximately 3.14159 (π). |
math.sin() | Module | Returns the sine of an angle in radians. For example, math.sin(math.pi / 2) returns 1.0. |
math.sqrt() | Module | Returns the square root. For example, math.sqrt(16) returns 4.0. Introduced in: |
math.tan() | Module | Returns the tangent of an angle in radians. For example, math.tan(math.pi / 4) returns approximately 1.0. |
math.trunc() | Module | Truncates a float toward zero. For example, math.trunc(3.9) returns 3 and math.trunc(-3.9) returns -3. |
math.e | Module | The mathematical constant e ≈ 2.71828 — the base of natural logarithms. |
math.pi | Module | The mathematical constant π ≈ 3.14159 — the ratio of a circle's circumference to its diameter. |
math.tau | Module | Equal to 2π (≈ 6.28318). math.tau is the ratio of a circle's circumference to its radius. |
math.inf | Module | Floating-point positive infinity. For example, math.inf > 10**100 is True. Use -math.inf for negative infinity. |
random.seed() | Module | Initializes the random number generator. For example, random.seed(42) makes all subsequent random calls produce the same sequence — useful for reproducible tests. Introduced in: |
random.random() | Module | Returns a random float in [0.0, 1.0). Introduced in: |
random.randint() | Module | Returns a random integer between a and b inclusive. For example, random.randint(1, 6) simulates a dice roll. Introduced in: |
random.randrange() | Module | Returns a randomly selected element from a range. For example, random.randrange(0,10,2) returns a random even number 0–8. |
random.choice() | Module | Returns a random element from a non-empty sequence. For example, random.choice(["rock","paper","scissors"]). Introduced in: |
random.choices() | Module | Returns a list of k elements chosen with replacement. For example, random.choices([1,2,3], k=5) picks 5 items (repeats allowed). |
random.shuffle() | Module | Shuffles a list in place. For example, random.shuffle(my_list) randomizes the order of elements. |
random.sample() | Module | Returns k unique elements from a population. For example, random.sample(range(50), 6) picks 6 unique lottery numbers. |
datetime.date() | Module | Creates a date object with year, month, and day. For example, datetime.date(2025, 6, 1) represents June 1, 2025. Introduced in: |
datetime.datetime() | Module | Creates a datetime combining date and time. For example, datetime.datetime(2025, 6, 1, 12, 0) represents noon on June 1, 2025. Introduced in: |
datetime.now() | Module | Returns the current local date and time. Introduced in: |
datetime.strftime() | Module | Formats a datetime as a string. For example, dt.strftime("%Y-%m-%d") returns '2025-06-01'. Introduced in: |
datetime.strptime() | Module | Parses a date string into a datetime object. For example, datetime.datetime.strptime("2025-06-01", "%Y-%m-%d"). |
datetime.timedelta() | Module | Represents a duration. For example, timedelta(days=7) is one week, and datetime.now() + timedelta(days=30) gives a date 30 days from now. Introduced in: |
statistics.mean() | Module | Calculates the arithmetic mean. For example, statistics.mean([1,2,3,4,5]) returns 3. Introduced in: |
statistics.median() | Module | Returns the middle value. For example, statistics.median([1,3,5]) returns 3. Introduced in: |
statistics.mode() | Module | Returns the most common value. For example, statistics.mode([1,2,2,3]) returns 2. Introduced in: |
statistics.stdev() | Module | Calculates the standard deviation from a sample of data. Introduced in: |
statistics.variance() | Module | Returns the sample variance — average squared deviation from the mean. Introduced in: |
re.search() | Module | Scans through a string and returns the first match, or None. For example, re.search(r"\d+", "score: 42") finds 42. Introduced in: |
re.match() | Module | Tests if the pattern matches at the start of the string. For example, re.match(r"hello", "hello world") returns a match. |
re.findall() | Module | Returns a list of all non-overlapping matches. For example, re.findall(r"\d+", "a1 b22 c333") returns ["1","22","333"]. Introduced in: |
re.sub() | Module | Replaces all occurrences of a pattern. For example, re.sub(r"\s+", " ", text) collapses multiple spaces into one. Introduced in: |
re.compile() | Module | Compiles a regex pattern into a reusable object for faster repeated use. Introduced in: |
re.split() | Module | Splits a string by pattern occurrences. For example, re.split(r"[,;]+", "a,b;;c") returns ["a","b","c"]. |
re.fullmatch() | Module | Returns a match only if the entire string matches. For example, re.fullmatch(r"\d{4}", "2025") matches but re.fullmatch(r"\d{4}", "2025x") does not. |
os.path.join() | Module | Joins path components with the OS separator. For example, os.path.join("home","user","file.txt") returns the right path for your OS. Introduced in: |
os.listdir() | Module | Returns a list of files and folders in a directory. For example, os.listdir(".") lists everything in the current directory. Introduced in: |
os.path.exists() | Module | Returns True if the path exists. For example, os.path.exists("data.txt") checks before opening. Introduced in: |
os.getcwd() | Module | Returns the current working directory as a string. |
os.environ | Module | A dict-like object of environment variables. For example, os.environ.get("PATH") reads the system PATH. |
json.dumps() | Module | Converts a Python object to a JSON string. For example, json.dumps({"name":"Alice","score":95}) returns a formatted JSON string. Introduced in: |
json.loads() | Module | Parses a JSON string and returns a Python object. For example, json.loads('{"name":"Alice"}') returns a dictionary. Introduced in: |
json.dump() | Module | Writes a Python object as JSON to a file. For example, json.dump(data, f, indent=2) writes nicely formatted JSON. Introduced in: |
json.load() | Module | Reads JSON from a file and returns the Python object. Introduced in: |
collections.Counter() | Module | Creates a counting dictionary. For example, Counter(["a","b","a"]) returns Counter({'a': 2, 'b': 1}). Introduced in: |
collections.defaultdict() | Module | Like a regular dict but auto-creates defaults for missing keys. For example, defaultdict(list) creates an empty list for any new key. Introduced in: |
collections.deque() | Module | A double-ended queue with O(1) appends/pops from both ends. Supports .appendleft() and .popleft(). Introduced in: |
collections.namedtuple() | Module | Creates a tuple subclass with named fields. For example, Point = namedtuple("Point", ["x","y"]); p = Point(1,2); p.x returns 1. Introduced in: |
functools.reduce() | Module | Applies a function cumulatively to reduce an iterable to one value. For example, reduce(lambda a,b: a+b, [1,2,3,4]) returns 10. Introduced in: |
__init__() | Object-Oriented Programming | The initializer method called when a new object is created. For example, def __init__(self, name): self.name = name sets the name attribute for every new instance. Introduced in: |
__str__() | Object-Oriented Programming | Defines the human-readable string representation returned by str(obj) and print(obj). For example, def __str__(self): return f"Learner: {self.name}". |
__repr__() | Object-Oriented Programming | Defines the developer-facing representation used by the REPL and repr(). Convention: return a string that looks like the constructor call. |
__len__() | Object-Oriented Programming | Allows len() to work on your object. For example, def __len__(self): return len(self.items) makes len(my_obj) work. |
__eq__() | Object-Oriented Programming | Defines equality comparison with ==. For example, def __eq__(self, other): return self.score == other.score makes objects equal when their scores match. |
__lt__() | Object-Oriented Programming | Defines less-than comparison with <. Implement this along with __eq__ to enable sorted() on your objects. |
__getitem__() | Object-Oriented Programming | Allows subscript access with obj[key]. For example, def __getitem__(self, key): return self.data[key]. |
__iter__() | Object-Oriented Programming | Makes an object iterable. For example, def __iter__(self): return iter(self.items) lets you use the object in a for loop. Introduced in: |
__next__() | Object-Oriented Programming | Returns the next value in a custom iterator. Raises StopIteration when exhausted. Introduced in: |
@classmethod | Object-Oriented Programming | Marks a method as a class method — receives the class (cls) as the first argument. For example, @classmethod def create(cls): return cls() is a factory method. Introduced in: |
@staticmethod | Object-Oriented Programming | Marks a method as static — receives neither self nor cls. Useful for utility functions that belong to the class namespace but need no instance. Introduced in: |
@property | Object-Oriented Programming | Turns a method into a read-only attribute accessor. For example, @property def full_name(self): return f"{self.first} {self.last}" lets you access it as obj.full_name. Introduced in: |
@property.setter | Object-Oriented Programming | Defines the setter for a @property. For example, @score.setter def score(self, v): self._score = max(0, v) validates on assignment. Introduced in: |
super() | Object-Oriented Programming | Returns a proxy referring to the parent class. Used in __init__() as super().__init__(name) to call the parent initializer. Introduced in: |
self | Object-Oriented Programming | The conventional first parameter of instance methods, referring to the object the method was called on. Python passes it automatically. Introduced in: |
inheritance | Object-Oriented Programming | A child class inheriting attributes and methods from a parent. For example, class PremiumLearner(Learner): gets everything Learner has, plus whatever it adds. Introduced in: |
encapsulation | Object-Oriented Programming | Bundling data and behaviour inside a class and controlling access. Prefix with _ to signal internal use, or __ for name mangling. Introduced in: |
polymorphism | Object-Oriented Programming | Different classes implementing the same method name in their own way. For example, both Dog and Cat can have a speak() method returning different sounds. Introduced in: |
indentation | Glossary | Python uses indentation (spaces at the beginning of a line) to define code blocks — there are no curly braces. The standard is 4 spaces per level. Inconsistent indentation raises IndentationError. Introduced in: |
variable | Glossary | A named container for storing data. For example, name = 'Alice' creates a variable called name holding the string 'Alice'. Python infers the type automatically. Introduced in: |
comment | Glossary | A note in code that Python ignores when running. A single-line comment starts with #. For example, # This prints the name. Comments explain the intent of the code. Introduced in: |
f-string | Glossary | A string literal prefixed with f that allows expressions inside {}. For example, f"Hello, {name}!" inserts the value of name directly into the string. Introduced in: |
slicing | Glossary | Extracting a portion of a sequence using [start:stop:step]. For example, "hello"[1:4] returns 'ell', and [1,2,3,4][::2] returns [1,3]. |
list comprehension | Glossary | A concise way to build a list using a for expression inside []. For example, [x**2 for x in range(5)] returns [0,1,4,9,16]. Introduced in: |
dict comprehension | Glossary | A concise way to build a dictionary. For example, {k: v**2 for k, v in items} creates a new dict with squared values. Introduced in: |
set comprehension | Glossary | A concise way to build a set. For example, {x.lower() for x in words} creates a set of lowercased words with no duplicates. Introduced in: |
generator expression | Glossary | Like a list comprehension but uses () and evaluates lazily. For example, sum(x**2 for x in range(100)) computes without building the whole list in memory. Introduced in: |
unpacking | Glossary | Assigning sequence elements to multiple variables in one line. For example, a, b, c = [1, 2, 3] assigns each item. Use *rest to catch extra items. Introduced in: |
*args | Glossary | Allows a function to accept any number of positional arguments. For example, def total(*args): return sum(args) lets you call total(1,2,3) or total(1,2,3,4,5). Introduced in: |
**kwargs | Glossary | Allows a function to accept any number of keyword arguments as a dictionary. For example, def profile(**kwargs): print(kwargs) collects all named arguments. Introduced in: |
decorator | Glossary | A function that wraps another function to add behaviour. Applied with @decorator_name above the function definition. For example, @staticmethod and @property are built-in decorators. Introduced in: |
walrus operator := | Glossary | Assigns a value and returns it in the same expression. For example, if n := len(data); n > 10: both stores and tests the length. Introduced in Python 3.8. Introduced in: |
iterator | Glossary | An object that implements __iter__() and __next__(), letting you step through values one at a time. All Python for loops use iterators internally. Introduced in: |
generator | Glossary | A function that uses yield to produce values lazily, one at a time. Unlike a list, it doesn't build all values in memory at once. For example, def count_up(n): for i in range(n): yield i. Introduced in: |
global scope | Glossary | Variables defined at module level (outside any function or class) are in the global scope — accessible from anywhere in the file. Introduced in: |
local scope | Glossary | Variables defined inside a function exist only while that function runs. They are destroyed when the function returns. Introduced in: |
module | Glossary | A file containing Python code that can be imported. For example, import math loads the built-in math module, giving access to functions like math.sqrt(). Introduced in: |
package | Glossary | A folder containing multiple modules and an __init__.py file. For example, import os.path uses the os package. |
pip | Glossary | Python's package manager. For example, pip install requests downloads and installs the requests library from PyPI. Introduced in: |
virtual environment | Glossary | An isolated Python environment where you install packages without affecting other projects. Created with python -m venv myenv. Introduced in: |



or