- **kwargs intermediate
A parameter written with a double star that gathers any extra keyword arguments into a dictionary. It lets a function accept named options it did not list, and forward them to other functions.
Example. def show(**kwargs): print(kwargs); show(a=1, b=2) prints {'a': 1, 'b': 2}.
Related: *args, Dictionary, Keyword argument
- *args intermediate
A parameter written with a leading star that gathers any extra positional arguments into a tuple. It lets a function accept a variable number of inputs. Inside the function you loop over it like any tuple, and the name args is only a convention.
Example. def total(*args): return sum(args); total(1, 2, 3) returns 6 because args is (1, 2, 3).
Related: **kwargs, Tuple, Positional argument
- Argument beginner
The actual value supplied to a function when calling it, which is matched to the function's parameters by position or by name. Arguments are what the caller provides; the function's parameters are the names that receive them inside the function.
Example. In power(2, 5) the values 2 and 5 are arguments passed to the parameters base and exp.
Related: Parameter, Positional argument, Keyword argument
- Arithmetic operator beginner
An operator that performs a mathematical calculation: + addition, - subtraction, * multiplication, / true division, // floor division, % modulo and ** exponentiation. Division with / always returns a float, even when the result is whole.
Example. 7 / 2 gives 3.5, 7 // 2 gives 3, 7 % 2 gives 1 and 2 ** 3 gives 8.
Related: Floor division, Modulo, Exponentiation
- Assignment beginner
The operation that binds a name to a value using the = sign. The right side is evaluated first, and the resulting object is then linked to the name on the left. In Python assignment does not copy data; it makes the name point at an object.
Example. x = 3 + 4 evaluates 3 + 4 to 7 and then binds the name x to 7.
Related: Variable, Expression, Augmented assignment
- Augmented assignment beginner
A shorthand operator that combines an arithmetic or bitwise operation with assignment, such as +=, -=, *=, /=, //= and %=. The statement x += 1 updates x using its old value. It is common for counters and running totals.
Example. total = 0; total += 250 makes total 250; a second total += 100 makes it 350.
Related: Assignment, Arithmetic operator, while loop
- break beginner
A statement that immediately exits the nearest enclosing loop, skipping any remaining iterations. It is used to stop early once a result is found or a stopping condition is met.
Example. for x in [4, 9, 12]: if x > 5: break stops at 9, so 12 is never visited.
Related: continue, for loop, Loop else clause
- Comment beginner
Text in a source file that the interpreter ignores, started with the # symbol and running to the end of the line. Comments explain why code does something for future readers. They should add reasoning, not repeat what the code obviously does.
Example. # convert paise to rupees on its own line, or total = paise / 100 # rupees after the code.
Related: Docstring, PEP 8, Statement
- Comparison operator beginner
An operator that compares two values and returns a boolean: == equal, != not equal, <, >, <= and >=. Python allows chaining, so a < b < c checks both comparisons at once. Comparing floats with == is risky because of rounding.
Example. score >= 40 returns True for 55. The chained test 0 <= x <= 100 checks that x lies between 0 and 100.
Related: Boolean, Logical operator, Float
- Conditional expression intermediate
A one-line form value_if_true if condition else value_if_false that chooses between two values inside an expression. It is Python's ternary operator, suited to short choices, while longer logic belongs in a normal if statement.
Example. label = 'pass' if marks >= 40 else 'fail' sets label to 'pass' when marks is 55.
Related: if statement, Expression, Boolean
- Constant beginner
A value that is not meant to change during a program. Python has no enforced constants, so by convention the name is written in uppercase, such as MAX_RETRIES, and treated as read-only.
Example. GST_RATE = 0.18 at the top of a file signals to readers that the value should not be reassigned.
Related: Variable, PEP 8, Identifier
- continue beginner
A statement that skips the rest of the current loop iteration and jumps to the next one. It helps to ignore unwanted items without nesting the rest of the body inside an if block.
Example. for n in range(5): if n % 2 == 0: continue; print(n) prints only 1 and 3.
Related: break, for loop, while loop
- Data type beginner
A category that tells Python what kind of value an object is and which operations it supports. Common built-in types are int, float, str, bool, list, tuple, set and dict. Types decide, for example, whether + adds numbers or joins text.
Example. type(3.5) returns float, while type('hello') returns str, so 3.5 + 1 works but 'hello' + 1 raises an error.
Related: Integer, Float, String, Boolean
- Debugging beginner
The process of finding and fixing the cause of incorrect behaviour in a program. Techniques include reading the traceback, printing intermediate values, using a debugger such as pdb to step through code, and reducing the failing case.
Example. A function returns 0 instead of 250; adding print(items) reveals an empty list, so the bug is in the code that fills it.
Related: Traceback, Exception, Assertion
- Deep copy intermediate
A copy of a container that recursively duplicates all nested objects, so the copy shares nothing mutable with the original. Made with copy.deepcopy(). It is safer for nested data but slower and uses more memory.
Example. import copy; b = copy.deepcopy(a) means changing b[0] never affects a[0], unlike a shallow copy.
Related: Shallow copy, Mutable, Module
- Default argument beginner
A parameter given a value in the function definition that is used when the caller omits it. Defaults make parameters optional. They are evaluated once, when the function is defined.
Example. def greet(name, greeting='Namaste'): return f'{greeting}, {name}'. greet('Ravi') uses the default 'Namaste'.
Related: Parameter, Mutable default argument, Keyword argument
- dict.get intermediate
A dictionary method that looks up a key and returns its value, or a default value (None unless given) if the key is missing. It avoids the KeyError that plain square-bracket lookup raises.
Example. prices = {'tea': 15}; prices.get('tea') is 15, prices.get('cake', 0) is 0, while prices['cake'] raises KeyError.
Related: Dictionary, KeyError, None
- Dictionary beginner
A mutable collection of key-value pairs, written in curly braces with colons, where each unique key maps to a value. Lookup by key is very fast on average. Since Python 3.7 a dictionary remembers the order in which keys were inserted.
Example. student = {'name': 'Kiran', 'age': 22}; student['name'] gives 'Kiran'; student['city'] = 'Kochi' adds a new pair.
Related: Hashable, dict.get, KeyError, Dictionary comprehension
- Dictionary comprehension intermediate
A compact expression that builds a dictionary from an iterable using key: value pairs, written {k: v for item in iterable if cond}. It is used to transform, filter or invert dictionaries.
Example. {name: len(name) for name in ['Ravi', 'Sita']} gives {'Ravi': 4, 'Sita': 4}.
Related: List comprehension, Dictionary, Set comprehension
- Docstring intermediate
A string literal placed as the first statement of a module, function or class to document it. Python stores it in the object's __doc__ attribute, and help() and editors display it. Triple quotes are conventional so it can span lines.
Example. def area(r): followed by """Return the area of a circle of radius r.""" lets help(area) print that sentence.
Related: Comment, Function, PEP 8
- Dynamic typing beginner
A property of languages where a variable has no fixed type; the type belongs to the value it currently refers to, and is checked while the program runs. In Python the same name can point to an int now and a string later, which is flexible but can hide mistakes until execution.
Example. x = 5 then x = 'five' is legal. Running 'five' + 5 fails only at that line with a TypeError.
Related: Variable, Data type, TypeError
- enumerate intermediate
A built-in function that wraps an iterable and yields pairs of a counter and the item, starting from 0 by default or from a chosen start. It avoids maintaining a separate index variable in loops.
Example. for i, name in enumerate(['A', 'B'], start=1): gives (1, 'A') and then (2, 'B').
Related: for loop, zip, Tuple unpacking
- Escape sequence beginner
A backslash followed by a character inside a string that stands for a special character, such as \n for a new line, \t for a tab, \\ for a backslash or \' for a quote. It lets you include characters that are hard to type directly.
Example. print('Name\tCity\nAsha\tPune') prints two lines with tab-separated columns.
Related: String, f-string
- Exception beginner
An event that occurs while a program runs and disrupts normal flow, represented by an object such as ValueError or KeyError. Unless it is caught, the exception ends the program with a traceback.
Example. int('abc') raises ValueError, and 10 / 0 raises ZeroDivisionError.
Related: try/except, Traceback, raise
- Exponentiation beginner
Raising a number to a power using the ** operator, meaning repeated multiplication of the base by itself. It has higher precedence than multiplication and associates right to left. A fractional exponent gives roots.
Example. 2 ** 10 gives 1024, 9 ** 0.5 gives 3.0, and 2 ** 3 ** 2 is evaluated as 2 ** 9, giving 512.
Related: Arithmetic operator, Operator precedence, Float
- Expression beginner
A piece of code that Python can evaluate to produce a value, such as 2 + 3, len(name) or x > 5. Expressions can be nested and used wherever a value is needed, including function arguments and the right side of an assignment.
Example. Evaluating (10 - 2) * 3 gives 24, and len('India') > 3 gives True.
Related: Statement, Operator, Operator precedence
- f-string beginner
A string literal prefixed with f that embeds expressions inside curly braces, which Python evaluates and inserts into the text. It supports format specifiers after a colon for width, decimals and alignment, making it the preferred way to build messages.
Example. name = 'Meera'; f'Hello {name}, total = {1234.5:.2f}' produces 'Hello Meera, total = 1234.50'.
Related: String, Expression, Escape sequence
- File I/O beginner
Reading data from and writing data to files using the built-in open() function, which returns a file object. The mode argument chooses reading ('r'), writing ('w'), appending ('a') or binary ('b'). Files should be closed after use.
Example. with open('notes.txt', 'w') as f: f.write('hello') creates a file containing hello.
Related: String, Exception
- filter intermediate
A built-in function that keeps only the items of an iterable for which a given function returns a true value, returning a lazy iterator. It is an alternative to a comprehension with an if.
Example. list(filter(lambda n: n > 2, [1, 3, 5])) gives [3, 5].
Related: map, Lambda, List comprehension
- finally intermediate
A block attached to try that always runs afterwards, whether or not an exception occurred, even when the block returns. It is used for cleanup such as closing files or releasing connections.
Example. try: f = open('a.txt') ... finally: f.close() makes sure the file is closed even if reading fails.
Related: try/except, Exception
- Float beginner
A number with a decimal point, stored as a binary floating-point value of type float. Floats are approximate because many decimal fractions cannot be represented exactly in binary, so tiny rounding errors appear in comparisons.
Example. 0.1 + 0.2 gives 0.30000000000000004, so use math.isclose(0.1 + 0.2, 0.3) instead of == when comparing.
Related: Integer, Data type, Comparison operator
- Floor division beginner
The // operator, which divides two numbers and rounds the result down to the nearest whole number toward negative infinity. It is used for tasks such as converting minutes to whole hours or splitting items into full batches.
Example. 135 // 60 gives 2 whole hours, and -7 // 2 gives -4, not -3, because it rounds down.
Related: Modulo, Arithmetic operator, Integer
- for loop beginner
A loop that runs its block once for each item of an iterable such as a list, string, dictionary or range, assigning the current item to a loop variable. It is used when the number of repetitions follows from the data.
Example. for city in ['Delhi', 'Chennai']: print(city) prints each name on its own line.
Related: while loop, range, Iterable
- frozenset advanced
An immutable version of a set. Its elements cannot be added or removed after creation, so it is hashable and can be used as a dictionary key or as an element of another set.
Example. key = frozenset({'a', 'b'}); d = {key: 1} works, while using a normal set as a key raises TypeError.
Related: Set, Immutable, Hashable
- global keyword intermediate
A statement that declares a name inside a function to refer to the module-level variable, so that assignments change the global instead of creating a local. Overuse makes code hard to follow.
Example. count = 0; def inc(): global count; count += 1 raises the module's count; without global it raises UnboundLocalError.
Related: Variable scope, LEGB rule
- Hashable advanced
Describes an object with a hash value that never changes during its lifetime and that can be compared for equality. Only hashable objects can be dictionary keys or set members. Immutable built-ins are hashable; lists, dicts and sets are not.
Example. hash('abc') works and {(1, 2): 'ok'} is valid, but {[1, 2]: 'x'} raises TypeError: unhashable type: 'list'.
Related: Dictionary, Set, Immutable
- Identifier beginner
The name given to a variable, function, class or module. A Python identifier may contain letters, digits and underscores, cannot start with a digit, is case-sensitive and cannot be a reserved keyword. Clear identifiers make code readable.
Example. total_marks and _temp are valid identifiers; 2nd_name and class are not. Total and total are different names.
Related: Variable, Keyword, PEP 8
- Identity operator intermediate
The is and is not operators, which test whether two names refer to the very same object in memory, not merely equal values. It is the correct way to test for None. For value equality use == instead.
Example. a = [1]; b = [1]; a == b is True but a is b is False. Write if x is None: for a None check.
Related: None, Comparison operator, Mutable
- if statement beginner
A control-flow statement that runs a block of code only when its condition is true. It can be extended with elif branches for extra conditions and an else branch for the remaining case. Python checks the branches in order and runs the first match only.
Example. if marks >= 75: grade='A' elif marks >= 60: grade='B' else: grade='C'. With marks 68 the grade becomes 'B'.
Related: Conditional expression, Boolean, Indentation
- Immutable beginner
Describes an object whose contents cannot change after creation. Integers, floats, strings, tuples, frozensets and bytes are immutable in Python. Any apparent change produces a new object, and immutability is what lets such objects be used as dictionary keys.
Example. s = 'cat'; s[0] = 'b' raises TypeError. s.replace('c', 'b') returns a new string 'bat' and leaves s unchanged.
Related: Mutable, Tuple, Hashable
- import statement beginner
The statement that loads a module and makes its contents available. Use import math, import math as m, or from math import sqrt. Python caches loaded modules, so a repeated import does not reload the file.
Example. import math then math.sqrt(16) gives 4.0; from math import sqrt lets you write sqrt(16).
Related: Module, Package
- Indentation beginner
The leading whitespace at the start of a line, which Python uses to mark blocks of code instead of braces. Statements under an if, loop or function must be indented consistently, and four spaces is the accepted convention. Wrong indentation causes an IndentationError.
Example. In if x > 0: the next line print('positive') must be indented four spaces to belong to the if block.
Related: Statement, if statement, PEP 8
- IndexError beginner
A built-in exception raised when a sequence index is outside the valid range of positions. It commonly appears in loops that run one step too far, or when code assumes a list has more items than it actually holds.
Example. nums = [1, 2, 3]; nums[3] raises IndexError: list index out of range, since valid indexes are 0 to 2.
Related: Indexing, List, Exception
- Indexing beginner
Accessing a single element of a sequence by its position, written with square brackets. Python counts from 0, so the first element is at index 0. Using an index beyond the end raises an IndexError.
Example. fruits = ['mango', 'apple', 'guava']; fruits[0] is 'mango' and fruits[2] is 'guava'; fruits[3] raises IndexError.
Related: Negative indexing, Slicing, IndexError
- Integer beginner
A whole number without a fractional part, of type int. Python integers can grow as large as memory allows, so there is no fixed overflow limit as in many other languages. They are used for counts, indexes and identifiers.
Example. population = 1_428_000_000 stores a large count; 2 ** 100 still gives an exact result.
Related: Float, Data type, Floor division
- json module intermediate
The standard-library module for converting between Python objects and JSON text. json.dumps turns objects into a string, json.loads parses a string, and json.dump and json.load work with files. It is the everyday tool for reading API responses and writing configuration files in Python programs.
Example. json.loads('{"a": 1}') gives {'a': 1}, and json.dumps({'a': 1}) gives the string '{"a": 1}'.
Related: Dictionary, String, Standard library
- KeyError beginner
A built-in exception raised when a dictionary lookup uses a key that is not present. Use in or dict.get to avoid it. The missing key is shown in the error message, which helps locate the mistaken lookup or a typo in the key.
Example. d = {'a': 1}; d['b'] raises KeyError: 'b', while d.get('b') returns None.
Related: dict.get, Dictionary, Exception
- Keyword beginner
A word reserved by Python with a fixed meaning in the syntax, such as if, for, while, def, return, import, True and None. Keywords cannot be used as identifiers. The keyword module lists them all.
Example. Writing for = 3 is a SyntaxError because for is a keyword. import keyword; keyword.kwlist prints the reserved words.
Related: Identifier, Syntax error, Statement
- Keyword argument beginner
An argument passed with the parameter name, in the form name=value, so its position does not matter. It makes calls self-explanatory and lets you skip parameters that have defaults. Keyword arguments improve readability when a function has many optional parameters.
Example. divide(b=2, a=10) gives 5.0, and print('x', end='') uses the keyword argument end.
Related: Positional argument, Default argument, **kwargs
- Lambda intermediate
A small anonymous function written in a single expression with the lambda keyword, without a name or a statement body. It is mostly used as a short argument to functions such as sorted, map and filter.
Example. sorted(['pear', 'fig', 'apple'], key=lambda w: len(w)) returns ['fig', 'pear', 'apple'].
Related: Function, sorted, map
- LEGB rule intermediate
The order in which Python searches for a name: Local scope of the current function, Enclosing functions, Global scope of the module, then Built-in names. The first match found is used.
Example. If x = 1 is global and a function also sets x = 2, code in the function sees 2 while the module still sees 1.
Related: Variable scope, Namespace, global keyword
- List beginner
An ordered, mutable sequence written in square brackets that can hold items of any type, including duplicates. Elements are reached by index, and methods such as append, insert, remove, pop, sort and extend change it in place.
Example. marks = [72, 85, 90]; marks.append(64) makes it [72, 85, 90, 64]; marks[1] is 85.
Related: Tuple, Indexing, List comprehension, Mutable
- List comprehension intermediate
A compact expression that builds a new list by applying an expression to each item of an iterable, optionally with a filtering condition, written [expr for item in iterable if cond]. It replaces many simple loops.
Example. [n * n for n in range(6) if n % 2 == 0] gives [0, 4, 16].
Related: Dictionary comprehension, Set comprehension, for loop
- Logical operator beginner
One of the keywords and, or and not, which combine or invert boolean conditions. and is true only if both sides are true, or is true if at least one side is, and not flips the value. They are used to build compound conditions.
Example. age >= 18 and has_id is True only when both hold. not is_empty flips a True into False.
Related: Boolean, Short-circuit evaluation, Truthiness
- Loop else clause advanced
An else block attached to a for or while loop that runs only if the loop finished without hitting break. It is used in search loops to handle the not found case without a flag variable.
Example. for n in nums: if n < 0: break; else: print('no negatives') prints only when the loop completes without break.
Related: break, for loop, while loop
- map intermediate
A built-in function that applies a given function to every item of an iterable and returns a lazy iterator of the results. It is an alternative to a list comprehension.
Example. list(map(len, ['a', 'bb', 'ccc'])) gives [1, 2, 3].
Related: filter, Lambda, List comprehension
- Membership operator beginner
The in and not in operators, which test whether a value occurs inside a container such as a string, list, tuple, set or dictionary. For dictionaries the test applies to keys. Lookup in sets and dictionaries is much faster than in lists.
Example. 'a' in 'banana' is True, 3 in [1, 2] is False, and 'name' in {'name': 'Ravi'} is True.
Related: Set, Dictionary, Iterable
- Module beginner
A single Python file containing definitions and statements that can be loaded into another program with import. Modules organise code into reusable units and give each file its own namespace.
Example. Saving def gst(p): ... in tax.py lets another file run import tax and call tax.gst(1000).
Related: Package, import statement, Namespace
- Modulo beginner
The % operator, which returns the remainder left after dividing one number by another. It is used to test even or odd, wrap around a cycle, and check divisibility. For positive divisors the result is never negative in Python.
Example. 17 % 5 gives 2 because 5 fits three times with 2 left over. n % 2 == 0 tests whether n is even.
Related: Floor division, Arithmetic operator, Comparison operator
- Mutable beginner
Describes an object that can be changed in place after it is created, without making a new object. Lists, dictionaries and sets are mutable in Python. Mutability matters because several names can share one object, so a change through one name is visible through the others.
Example. a = [1, 2]; b = a; b.append(3) makes a equal to [1, 2, 3] too, because both names point to the same list.
Related: Immutable, List, Shallow copy
- Mutable default argument intermediate
A well-known pitfall where a mutable object such as a list is used as a default value. Because defaults are created once at definition time, the same object is shared across calls and accumulates changes. The safe pattern is to default to None and create the list inside.
Example. def add(x, items=[]): items.append(x); return items returns [1] then [1, 2] on successive calls. Use items=None instead.
Related: Default argument, Mutable, None
- Namespace intermediate
A mapping from names to objects, such as the built-ins, a module's globals or a function's locals. Different namespaces let the same name exist in separate places without clashing. Namespaces are how Python keeps names from different modules and functions from colliding with each other.
Example. math.pi and my_module.pi are different names in different namespaces, so they do not conflict.
Related: Variable scope, Module, LEGB rule
- Negative indexing beginner
Using negative numbers as positions counted from the end of a sequence, where -1 is the last element, -2 the second last, and so on. It avoids computing the length to reach elements near the end.
Example. For nums = [10, 20, 30, 40], nums[-1] is 40 and nums[-2] is 30.
Related: Indexing, Slicing, List
- None beginner
The single built-in value that represents the absence of a meaningful value. It is the only instance of type NoneType and is what a function returns when it has no return statement. Test for it with the is operator, not ==.
Example. def greet(): print('hi') returns None, so result = greet() sets result to None. Use if result is None: to check it.
Related: Return value, Identity operator, Truthiness
- Operator beginner
A symbol or keyword that performs an operation on one or more values called operands. Python groups them into arithmetic, comparison, logical, bitwise, assignment, identity and membership operators. Operators combine values into expressions.
Example. In 7 + 3 the plus operator adds two operands to give 10, and in not True the keyword not gives False.
Related: Expression, Arithmetic operator, Operator precedence
- Operator precedence beginner
The fixed order in which Python evaluates operators when an expression has several. Exponentiation comes first, then multiplication and division, then addition and subtraction, then comparisons, then not, and, or. Parentheses override the order.
Example. 2 + 3 * 4 gives 14, not 20, because * binds tighter than +. (2 + 3) * 4 gives 20.
Related: Expression, Arithmetic operator, Logical operator
- pass beginner
A statement that does nothing. It fills a place where Python's syntax requires a statement, such as an empty function or if block that you plan to write later. It is a placeholder, similar to an empty statement.
Example. def load_data(): pass defines a function whose body is not yet written but is still valid syntax.
Related: Statement, Function, Indentation
- Pass by object reference advanced
Python's argument-passing model: a function receives a reference to the same object the caller has. Mutating a mutable argument inside the function is visible outside, but rebinding the parameter name is not.
Example. def f(lst): lst.append(1) changes the caller's list, while lst = [] inside f does not.
Related: Mutable, Argument, Variable scope
- PEP 8 intermediate
Python's official style guide, which sets conventions such as four-space indentation, lowercase_with_underscores names for functions and variables, and a maximum line length of 79 characters. Following it makes code consistent across teams.
Example. A function named calculate_total follows PEP 8, while CalculateTotal or calcTotal for a function does not.
Related: Identifier, Indentation, Docstring
- Positional argument beginner
An argument matched to a parameter by its order in the call. Changing the order changes which parameter receives which value. Positional arguments must come before keyword arguments. Mixing up the order silently gives wrong results, so it is safest with few parameters.
Example. For def divide(a, b), divide(10, 2) gives 5.0 but divide(2, 10) gives 0.2.
Related: Keyword argument, Argument, Parameter
- raise intermediate
A statement that deliberately triggers an exception, either a new one or the current one again. It signals an error condition to the caller, for example when the input is invalid.
Example. if age < 0: raise ValueError('age cannot be negative') stops the function with that message.
Related: Exception, ValueError, try/except
- range beginner
A built-in immutable sequence type representing an arithmetic progression of integers, created as range(stop), range(start, stop) or range(start, stop, step). It generates numbers lazily, so it uses little memory even for huge ranges. The stop value is excluded.
Example. list(range(2, 10, 3)) gives [2, 5, 8], and for i in range(3) visits 0, 1, 2.
Related: for loop, Iterable, Slicing
- REPL beginner
The read-eval-print loop, an interactive prompt where you type Python code, see the result immediately and try ideas quickly. It is useful for testing small snippets and exploring libraries. Beginners use it to experiment, and it pairs well with the help() function for reading documentation.
Example. Typing 2 + 3 at the >>> prompt prints 5 straight away.
Related: Interpreter, Expression, Debugging
- Return value beginner
The result a function sends back to its caller with the return statement, which also ends the function immediately. A function with no return statement returns None. It can return several values as a tuple.
Example. def stats(nums): return min(nums), max(nums) gives (2, 9) for [2, 5, 9], which can be unpacked as lo, hi.
Related: Function, None, Tuple unpacking
- Sequence intermediate
An ordered collection whose items are reached by integer position and that supports len(), indexing and slicing. Lists, tuples, strings and ranges are sequences, while sets and dictionaries are not.
Example. len('hello') is 5 and 'hello'[1:3] is 'el'; both work on any sequence, including [10, 20, 30] and range(5).
Related: Indexing, Slicing, Iterable
- Set beginner
An unordered, mutable collection of unique, hashable elements written in curly braces. It removes duplicates automatically and tests membership very fast. It supports union, intersection and difference operations. Sets are handy for removing duplicates and for fast membership tests on large data.
Example. set([1, 2, 2, 3]) gives {1, 2, 3}. {1, 2} | {2, 3} gives {1, 2, 3} and {1, 2} & {2, 3} gives {2}.
Related: frozenset, Hashable, Membership operator, Dictionary
- Set comprehension intermediate
A compact expression that builds a set from an iterable, written {expr for item in iterable if cond}. Duplicates are removed automatically, so it is useful for collecting unique values.
Example. {word.lower() for word in ['Hi', 'HI', 'hello']} gives {'hi', 'hello'}.
Related: List comprehension, Set, Dictionary comprehension
- Shallow copy intermediate
A copy of a container that duplicates the outer object but keeps references to the same inner objects. Changing a nested mutable item through one copy therefore also changes it in the other. Made with copy.copy(), list.copy() or slicing.
Example. a = [[1], [2]]; b = a.copy(); b[0].append(9) also changes a[0], which becomes [1, 9].
Related: Deep copy, Mutable, List
- Short-circuit evaluation intermediate
The rule that and/or stop evaluating as soon as the result is known. In A and B, B is skipped if A is false; in A or B, B is skipped if A is true. This avoids unnecessary work and can guard against errors.
Example. if d != 0 and total / d > 2: never divides by zero, because when d is 0 the second part is not evaluated.
Related: Logical operator, Truthiness, if statement
- Slicing beginner
Extracting a sub-sequence with the form seq[start:stop:step]. The start is included and the stop is excluded; any part may be omitted. Slicing returns a new object and never raises an error for out-of-range bounds.
Example. 'abcdef'[1:4] gives 'bcd', 'abcdef'[::2] gives 'ace', and [1, 2, 3][::-1] reverses the list to [3, 2, 1].
Related: Indexing, String, List
- sorted beginner
A built-in function that returns a new sorted list from any iterable, leaving the original untouched. It accepts a key function to choose what to sort by and reverse=True for descending order. The sort is stable.
Example. sorted([3, 1, 2]) gives [1, 2, 3]; sorted(names, key=len, reverse=True) puts the longest names first.
Related: List, Lambda, Iterable
- Standard library beginner
The collection of modules that ship with Python, covering tasks such as maths, dates, files, JSON, regular expressions and networking, with no installation needed. Knowing it avoids reinventing common tools.
Example. import json, datetime, random and pathlib are all standard-library modules.
Related: Module, import statement
- Statement beginner
A complete instruction that Python executes to perform an action, such as an assignment, an if block, a loop, an import or a return. Unlike an expression, a statement does not itself produce a value that can be used inside another expression.
Example. x = 5, import math and for i in range(3): are each statements; you cannot write y = (import math).
Related: Expression, Assignment, Indentation
- String beginner
An immutable sequence of characters of type str, written in single, double or triple quotes. Strings hold text such as names, messages and file paths, and support indexing, slicing and many built-in methods for searching and changing case.
Example. name = 'Asha' has length 4, and name[0] is 'A'. name.upper() returns a new string 'ASHA'.
Related: Indexing, String method, f-string, Immutable
- String method beginner
A function attached to a string object and called with dot notation, such as upper(), lower(), strip(), split(), join(), replace(), find() and startswith(). Because strings are immutable, these methods return new strings instead of changing the original.
Example. ' Hi, there '.strip().split(',') returns ['Hi', ' there'], and '-'.join(['a', 'b']) returns 'a-b'.
Related: String, Immutable, Escape sequence
- Syntax error beginner
An error found before the program starts, because the code breaks the grammar rules of the language, such as a missing colon, unmatched bracket or bad indentation. The program will not run until it is fixed.
Example. if x > 3 print(x) raises SyntaxError because the colon after the condition is missing.
Related: Indentation, Keyword, Interpreter
- Traceback beginner
The report Python prints for an uncaught exception, listing the chain of function calls that led to the error, most recent call last, and ending with the exception type and message. It is the first thing to read when debugging.
Example. A traceback ending in KeyError: 'age' at line 12 tells you the dictionary lookup on that line failed.
Related: Exception, KeyError, Debugging
- Truthiness intermediate
The way Python treats any object as true or false when a boolean is needed. False, None, zero, and empty containers or strings are falsy; almost everything else is truthy. It allows concise checks such as if items:.
Example. if []: is false and if 'hi': is true. name = user_input or 'guest' uses 'guest' when the input is an empty string.
Related: Boolean, None, Logical operator
- try/except beginner
A construct that runs a block of code and, if it raises an exception, jumps to a matching except block to handle it instead of crashing. You can name the exception types to catch and add an else block for the no-error case.
Example. try: n = int(text) except ValueError: n = 0 sets n to 0 when text is 'abc'.
Related: Exception, finally, raise
- Tuple beginner
An ordered, immutable sequence written in parentheses with commas. Once created, its elements cannot be replaced. Tuples suit fixed groups of values such as coordinates, function return values and dictionary keys.
Example. point = (12.9, 77.6) stores latitude and longitude; point[0] = 13 raises TypeError.
Related: List, Immutable, Tuple unpacking, Hashable
- Tuple unpacking intermediate
Assigning the items of a sequence to several names in one statement, matched by position. The number of names must match the number of items unless a starred name is used. It is also used to swap values without a temporary variable.
Example. x, y = (3, 4) sets x to 3 and y to 4. a, b = b, a swaps two variables.
Related: Tuple, Assignment
- Type conversion beginner
Changing a value from one type to another by calling the target type as a function, such as int(), float(), str() or list(). Conversion is often needed because input() returns text and arithmetic needs numbers. Invalid input raises a ValueError.
Example. int('42') gives 42, float('3.5') gives 3.5, and int('abc') raises ValueError. list('hi') gives ['h', 'i'].
Related: Data type, ValueError, String
- TypeError beginner
A built-in exception raised when an operation is applied to an object of the wrong type, such as adding a string to an integer or calling a non-callable. Reading the message tells you which types were involved, which usually points straight at the faulty line.
Example. 'age: ' + 25 raises TypeError; the fix is 'age: ' + str(25).
Related: ValueError, Dynamic typing, Exception
- ValueError beginner
A built-in exception raised when a function receives an argument of the right type but an unsuitable value. It is common when converting text to numbers. It is usually caught with try/except when handling user input, so a program can ask again instead of crashing.
Example. int('12.5') and math.sqrt(-1) both raise ValueError.
Related: TypeError, Type conversion, Exception
- Variable beginner
A name that refers to a value stored in memory. You create it by assigning a value to the name, and later code uses the name to read or replace that value. Variables let a program keep track of data such as counts, text or results as it runs.
Example. price = 499 creates a variable called price that refers to the integer 499; later price = price * 2 makes it refer to 998.
Related: Assignment, Data type, Identifier
- Variable scope beginner
The region of a program where a name is visible and can be used. Names created inside a function are local to it and vanish when it ends, while names at the top of a file are global.
Example. def f(): y = 5 makes y exist only inside f; print(y) outside raises NameError.
Related: LEGB rule, global keyword, Namespace
- Walrus operator advanced
The := operator, introduced in Python 3.8, which assigns a value to a name as part of an expression. It lets you compute a value once, use it in a condition, and reuse it without a separate statement.
Example. if (n := len(data)) > 10: print(n) computes the length once and reuses it inside the block.
Related: Assignment, Expression, while loop
- while loop beginner
A loop that keeps running its block as long as a condition stays true, checking the condition before each pass. It suits cases where the number of repetitions is unknown in advance. The body must change something so the condition eventually becomes false.
Example. n = 3; while n > 0: print(n); n -= 1 prints 3, 2, 1 and stops.
Related: for loop, break
- ZeroDivisionError beginner
A built-in exception raised when a number is divided, floor-divided or reduced by modulo with zero as the divisor. It is a common bug when computing averages or ratios over empty data, and it is easy to guard against with a check.
Example. total / count raises ZeroDivisionError when count is 0, so check if count: first.
Related: Exception, Arithmetic operator, try/except
- zip intermediate
A built-in function that combines several iterables element by element, yielding tuples of matching positions and stopping at the shortest input. It is used to loop over parallel lists or build dictionaries from keys and values.
Example. list(zip([1, 2, 3], ['a', 'b'])) gives [(1, 'a'), (2, 'b')], and dict(zip(keys, values)) builds a dictionary.
Related: enumerate, Tuple, Dictionary