def Defines a function
return This statement returns a value from the function. It provides
the output of the function and ends its execution.
Random() Returns a random floating point between 0 and 1
Randint(a,b) Returns a random integer between a and b
Randrange(start, stop) Returns a random number from a range
Seed() Sets the seed value for the random number generator. Using
the same seed will produce reproducible results, which is
useful for testing.
from math import ceil,
floor
ceil() Rounds up a number to the nearest integer
floor() Rounds down a number to the nearest integer
from math import * Brings in all math identifiers
Map() applies a function to every element in a sequence
Filter() applies a function to every element and keeps only those
where the function returns True
range(len(list)) to loop through list indices and values.
Type(..) Shows variable/list type
Enumerate() Keeps track of index and value over a loop
del used to delete elements, slices, or entire variables.
It can remove items from a list by index or slice, or completely
delete a variable from memory.
.sort() arranges elements in ascending order (smallest to largest).
.sort(reverse=True) arranges elements in descending order (smallest to
largest).
sorted() returns a new sorted list, leaving the original
sequence unchanged.
WHEN APPLIED TO A TUPLE , GIVES A NEW LIST
.index() Returns the position of the first occurrence of the value
You can specify where the search begins by adding a starting
index as a second argument (-,-)
in Checks existence
Not in Checks non existnse
Key Value that we are looking for
Any() any(iterable) → Returns True if any element is True.
All() all(iterable) → Returns True if every element is True.
• Nonzero numbers → True
• Zero → False
• Non-empty collections (lists, tuples, strings) → True
• Empty collections → False
.insert(index, value) to insert an element at a specific position.
.append(value) to add one element to the end of the list.
.extend(iterable) to add all elements of another iterable (like a list, string, or
tuple) to the end.
.remove(value) to delete the first occurrence of a specific value.
.clear() . to remove all elements from a list
.count(value) to count how many times a value appears in a list.
reverse() to reverse the order of list elements in place (modifies the
original list).
copy() to create a shallow copy of a list.
filter(function, keeps only elements for which the given function
iterable) returns True.
lambda a small, anonymous function written inline.
map(function, iterable) transforms each element of an iterable using the given
function.
Reduce () A reduction processes a sequence into a single value,
such as a total, minimum, or maximum.
Module A module is a file containing Python code (functions, variables,
etc.) that you can reuse.
Standard Library The Standard Library is a collection of modules that come built-
in with Python.
Scope determines where it can be used in a program.
Local scope A variable defined inside a function is local.
It exists only within that function and disappears once the
function ends.
Global scope Identifiers defined outside any function or class have global
scope.
These include functions, variables, and classes defined at the
top level of a program.
They can be used anywhere in the file after they are defined.
import statistics as You can use the as keyword to give a module (or identifier) a
stats shorter or more convenient name.
function-call stack Functions call other functions. Python keeps track in a call
stack.
A pure function - Depends only on its input arguments
- Always produces the same output for the same input
- Has no side effects (does not modify data outside its scope)
statistics Built-in Python module for statistical calculations
[Link] Popular plotting library for creating graphs
list collection of ordered items that can be changed (mutable).
strings and tuples immutable, you can access their elements, but you cannot
change them
Appending Strings When the right-hand side of += is an iterable (like a string or
and Tuples tuple),
each element is added individually to the list.
Eg list = []
List+= “python”
Print(list)
[‘p’ , ‘y’, ‘t’…….]
Concatenating Lists Joining two lists with +
tuples - Cannot be changed
- Can be created with commas
- tuples can be concatenated using +=, which creates
a new tuple.
- += can be used with same type (doesn’t add list to a tuple
)
- += can add elements of a tuple to list (appending)
- Tuples Can Contain Mutable Objects e.g list
One element tuple Need a comma after the element
Unpacking allows you to assign elements of any sequence (list, tuple,
string, or range)
directly to multiple variables in a single statement.
The number of variables on the left must exactly match the
number of elements in the sequence.
You can swap variable values easily without a temporary
variable
by packing them into a tuple on the right and unpacking on the
left.
Sequence Slicing allows you to extract portions (subsequences) of sequences like
lists, tuples, or strings.
A slice creates a new sequence of the same type containing the
selected elements.
General form: sequence[start:end:step]
• start → index where the slice begins (inclusive)
• end → index where the slice ends (exclusive)
• step → how many items to skip (optional)
If the starting index is omitted, Python assumes it’s `0`.
If the ending index is omitted, Python assumes it’s the
sequence’s length.
If both start and end are omitted, the slice copies the entire
sequence.
Slicing can also replace, delete, or insert elements in mutable
sequences like lists.
Last-In, First-Out A stack is a data structure that stores elements in Last-In, First-
(LIFO) order. Out (LIFO) order
The last item added (“pushed”) is the first item removed
(“popped”).
We’ll create an empty list called stack, then use:
• .append(x) → to push an item onto the stack
• .pop() → to pop (remove and return) the most recent item
Stacks are used in:
• Function calls (call stack)
• Undo/Redo operations
• Expression parsing
• Backtracking algorithms
REVISE LIST WEEK 5
COMPREHENSION they immediately build and store the entire list.
PART FROM SLIDES
Operation Description Example
Create list from
Basic creation range
[x for x in range(5)]
[x**2 for x in
Mapping Transform each item
range(5)]
Include items [x for x in range(10)
Filtering meeting condition if x % 2 == 0]
Processing Apply function to [[Link]() for s in
iterables each element words]
Generator look similar to list comprehensions but
expressions use parentheses () instead of square brackets [].
they produce one value at a time as you iterate over them.
Use list comprehensions for small or reusable collections,
and generator expressions for large or one-time sequences to
save memory and improve performance.
• filter → select items
• map → transform items
• reduce → combine items
• All use lazy evaluation — results are generated only
when needed.
• List comprehensions often combine these concepts in a
cleaner, Pythonic way.
A two-dimensional (also called a nested list or matrix) is a list that contains other
list lists as its elements.
Matplotlib (plt) Core plotting engine
NumPy (np) High-speed math and array processing
random Generate random die rolls
Seaborn (sns) Beautiful, easy plotting built on Matplotlib
Arrays
[Link] : Number of rows
[Link] : number of rows into number of columns
dtype : data type
.size: Total number of elements.
.itemsize: Memory (in bytes) per element.
.flat : allows you to iterate through a multidimensional array as if it were one-dimensional.
.zeros : array of zeroes
.ones : array of ones
.full(_,_) : array filled with specific value
[Link] :is used to createanarraywithregularsteps
optimized for array creation and performs faster than using Python's built-in range.
arange doesn’t support strings
Creating Floating-Point Ranges with linspace
[Link]: (start, stop, num)
arange(1, 21) : creates values 1–20
.reshape(4, 5) : converts 1D array → 4×5 matrix
Comparisons are performed element-wise, producing Boolean arrays indicating the
comparison results.
Numbers[0,1]: [row 0 , column 1]
To select an element in a two-dimensional array, specify its row and column indices.
.view() : creates a shallow copy changes effect both
.copy(): deep , copy , both have independent data
reshape : returns a view (shallow copy) of the array with new dimensions (does not modify
the original).
resize : modifies the original array’s shape.
flatten : creates a deep copy — independent of the original.
ravel : creates a view — changes reflect in the original.
.T : transpose
Hstack and vstack :can combine arrays either by adding columns (horizontal stack) or
rows (vertical stack)
pandas Series
A Series is an enhanced one-dimensional array that supports:
Custom (non-integer) indices
Missing data handling
Vectorized operations
you can use strings or other immutable types as indices (grades = [Link]([87, 100, 94],
index=['Wally', 'Eva', 'Sam']))
.[Link]() : method returns a boolean Series.
A DataFrame is an enhanced two-dimensional array that supports:
Custom row and column indices
Missing data handling
Mixed data types across columns
Each column in a DataFrame is a Series.
We can specify custom row labels using the index keyword or the .index attribute.
We can select rows using .loc (by label) or .iloc (by integer index).
Use .at and .iat for fast access to single elements.
Strings
Use + before the field width to display a sign for positive and negative numbers
To pad with zeros instead of spaces, place a `0` before the field width (after the sign
symbol, if used).
You can format numbers with thousands separators using a comma (,).
You call format() on a format string containing curly brace {} placeholders,
optionally including format specifiers (after a colon :).
.strip() : remove both leading and trailing whitespace.
.lstrip() : remove only leading (left-side) whitespace.
.rstrip() : remove only trailing (right-side) whitespace
.capitalize() : returns a copy of the string with only the first character capitalized
.title() : capitalizes the first character of each word,
count() : returns the number of times a substring occurs in the string.
index() : returns the first index where a substring is found.
index() and rindex(), : instead of raising an error, they return -1 if the substring is not found.
split() : breaks a string into a list of substrings based on a delimiter (default: whitespace).
join() : concatenates elements of an iterable (like a list) into a single string, separated by
the string on which join() is called.
partition() splits a string into a tuple of three parts:
The part before the separator,
The separator itself,
The part after the separator.
rpartition() : works the same way but searches from the end of the string.
splitlines() : splits a string at each newline (\n) character and returns a list of lines.
isdigit() : returns True if all characters in the string are digits (0–9).
isalnum() : returns True if the string contains only letters and digits, and False if it contains
spaces or symbols.
Python provides raw strings, which are preceded by the letter r. Raw strings treat
backslashes as literal characters, not as escape indicators.
re : module provides built-in support for working with regular expressions.
[Link](pattern, string) checks if the entire string matches the given pattern.
re provides special symbols (metacharacters) for matching groups of characters.
For example, \d matches any digit (0–9).
The quantifier {5} means exactly five repetitions.
Square brackets [] define a set of valid characters.
For example:
[A-Z] matches any uppercase letter
[a-z] matches any lowercase letter
[A-Z][a-z]* matches a capitalized name (like "Wally")
A caret ^ at the start of brackets negates the class meaning any character except those
listed.
ou can specify how many times a character or group should appear:
• {n,} → at least n times
• {n,m} → between n and m times (inclusive)
The re module provides two powerful functions for string manipulation:
• [Link]() — replaces substrings that match a given pattern.
• [Link]() — splits a string into parts based on a pattern.
• [Link](pattern, replacement, string, count=0)
• [Link](pattern, string, maxsplit=0)
re module provides several ways to search for patterns in strings and access matches:
• search() — finds the first match anywhere in the string
• match() — matches only at the beginning of a string
• findall() — returns all matches as a list
• finditer() — returns an iterator of match objects
flags=[Link] argument to perform case-insensitive searches:
Anchors: Beginning (^) and End ($)
• ^ → matches start of a string
• $ → matches end of a string