You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Use dir(variable) to list all available methods for any object
Object Types & Type System
Built-in Object Type Overview
Object Type
Examples
Immutable?
Notes
Numbers
1234, 3.1415, 3+4j, 0b111, Decimal(), Fraction()
✓
Unlimited precision integers
Strings
'spam', "bos's", b'a\x01c', u'sp\xc4m'
✓
Sequences of text
Lists
[1, [2, 'three'], 4.5], list(range(10))
✗
Ordered, mutable sequences
Tuples
(1, 'spam', 4, 'U'), tuple('spam'), namedtuple
✓
Fixed, immutable sequences
Dictionaries
{'food': 'spam', 'taste': 'yum'}, dict(hours=10)
✗
Key-value mappings
Sets
set('abc'), {'a', 'b', 'c'}
✗
Unordered unique collections
Files
open('eggs.txt'), open(r'C:\ham.bin', 'wb')
—
I/O streams
Booleans
True, False
✓
Truth values
Program Units
functions, modules, classes
—
Code organization
Key Concepts:
Immutability: Numbers, Strings, Tuples cannot be modified after creation
Mutability: Lists, Dictionaries, Sets are mutable (can be changed in-place)
Type Checking (Use Sparingly!)
# Bad practice - avoids polymorphismtype(L) ==list# Better - use isinstance for type checkingisinstance(L, list)
isinstance(x, (list, tuple)) # Check multiple types# Best - use duck typing (Pythonic way)# Don't ask "what is it?", ask "what can it do?"
Numeric Types
Numeric Literals
Literal
Interpretation
1234, 24
Integers (unlimited size)
1.23, 1.3e-10, 4E210
Floating-point numbers
0o117, 0x9ff, 0b10101
Octal, hexadecimal, binary
3+4j, 3.0+4.0j, 3J
Complex numbers
set('spam'), {1, 2, 3, 4}
Sets
Decimal('1.0'), Fraction(1, 3)
Decimal and fraction extensions
bool(x), True, False
Boolean type and constants
Numeric Display & Representation
# Precision vs. user-friendly display3.1415*2# Full precision: 6.28300000004print(3.1415*2) # User-friendly: 6.283# Formatted output'%e'%num# Scientific: '3.333e-01''%4.2f'%num# Fixed-point: '0.33''{0:4.2f}'.format(num) # Format method: '0.33'
Numeric Operations
# Built-in numeric functionspow(x, y) # Power: x^yabs(x) # Absolute valueround(x, ndigits) # Round to n decimalsint(x) # Convert to int (truncates float)float(x) # Convert to floathex(x) # Convert to hex string: '0xf'oct(x) # Convert to octal string: '0o17'bin(x) # Convert to binary string: '0b1111'# Conversion with baseint('0xf', 16) # Parse hex: 15int('0o17', 8) # Parse octal: 15
Math Module (Standard Library)
importmath# Constantsmath.pi# 3.141592...math.e# 2.71828...# Functionsmath.sqrt(x) # Square rootmath.sin(x), math.cos(x), math.tan(x) # Trigonometrymath.floor(x) # Round towards negative infinitymath.ceil(x) # Round towards positive infinitymath.trunc(x) # Discard fractional partmath.min(), math.max() # Min and max functions
Random Module (Standard Library)
importrandomrandom.random() # Random float [0.0, 1.0)random.randint(a, b) # Random integer [a, b]random.choice(sequence) # Random element from sequencerandom.shuffle(list) # Shuffle list in-place
# Python allows chained comparisonsX<Y<Z# True (equivalent to: X < Y AND Y < Z)X<Y>Z# Works as expected1<2<3.0<4# True1==2<3# Same as: 1 == 2 AND 2 < 3# Warning: Floating-point comparisons1.1+2.2==3.3# May not be True due to rounding# 1.1 + 2.2 = 3.3000000000000003int(1.1+2.2) ==3# This works
S='Spam'# Length and accesslen(S) # 4S[0] # 'S' (first)S[-1] # 'm' (last)S[-2] # 'a' (second from end)# SlicingS[1:3] # 'pa' (excludes end index)S[0:3] # 'Spa'S[1:] # 'pam' (to end)S[:-1] # 'Spa' (everything but last)S[::2] # 'Sm' (every other character)S[::-1] # 'mapS' (reversed)# OperationsS+'xyz'# Concatenation: 'Spamxyz'S*3# Repetition: 'SpamSpamSpam''ab'in'cabsf'# Membership: True
String Slicing & Indexing Visualization
Index: 0 1 2 3 4 5 6 7
| S | L | I | C | E | S | B | C |
Index: -8 -7 -6 -5 -4 -3 -2 -1
String Methods
Method
Example
Output
Notes
find
S.find('pa')
1
Return index or -1 if not found
replace
S.replace('pa', 'XYZ')
'SXYZm'
Strings are immutable
split
'a,b,c'.split(',')
['a', 'b', 'c']
Split by delimiter
upper
S.upper()
'SPAM'
Convert to uppercase
lower
S.lower()
'spam'
Convert to lowercase
strip
' spam '.strip()
'spam'
Remove leading/trailing whitespace
rstrip
'spam\n'.rstrip()
'spam'
Remove trailing chars (default: whitespace)
lstrip
' spam'.lstrip()
'spam'
Remove leading chars
isalpha
S.isalpha()
True/False
All alphabetic?
isdigit
'123'.isdigit()
True
All digits?
startswith
S.startswith('S')
True/False
Starts with substring?
endswith
S.endswith('m')
True/False
Ends with substring?
join
','.join(['a', 'b'])
'a,b'
Join iterable with delimiter
count
'aaa'.count('a')
3
Count occurrences
encode
'spam'.encode('utf8')
b'spam'
Encode to bytes
String Immutability
S='spam'S[0] ='z'# Error! Strings are immutable# Correct approachS='z'+S[1:] # Create new string: 'zpam'
String Formatting
Old-style % formatting
'%s, %s'% ('eggs', 'SPAM') # 'eggs, SPAM''There are %d %s'% (2, 'birds') # 'There are 2 birds'# Formatting with dictionary'%(qty)d more %(food)s'% {'qty': 1, 'food': 'spam'} # '1 more spam'
Method-style .format() — Python 3.0+
# By position'{0},{1},{2}'.format('spam', 'ham', 'eggs') # 'spam,ham,eggs'# By keyword'{motto},{pork},{food}'.format(motto='spam', pork='ham', food='eggs')
# Mixed'{motto},{0},{food}'.format('ham', motto='spam', food='egg') # 'spam,ham,egg'# Relative position (no indices)'{},{},{}'.format('spam', 'ham', 'eggs')
# Accessing attributes'My {0.platform}'.format(sys) # 'My win32''My {map[kind]}'.format(map={'kind': 'laptop'}) # 'My laptop'
F-strings — Python 3.6+
name, age='Bob', 40f'Hello {name}, age {age}'# f'Hello Bob, age 40'f'{name.upper()}'# f'BOB'f'{2**8}'# f'256'f'{value:.2f}'# f-string formatting
Special String Types
Raw strings — Backslashes not interpreted
myfile=open(r'C:\new\text.dat', 'w') # \n is not interpreted as newline
Triple-quoted strings — Multi-line text
mantra="""Always lookon the brightside of life."""# Common uses:# 1. Docstrings for functions/classes# 2. Temporarily disable code (act as block comments)# 3. Embed quotes easilyX=1"""import osprint(os.getcwd())"""Y=2# Code in triple quotes is ignored
Byte strings — Python 3.0+
b'a\x01c'# Byte literals (ASCII only)'spam'.encode('utf8') # Encode string to bytes: b'spam'b'spam'.decode('utf8') # Decode bytes to string: 'spam'
# Read entire filetext=f.read() # Single string (NOT one line!)lines=f.readlines() # List of lines (with \n)# Read line by lineline=f.readline() # Single line with \nchar=f.read(N) # N characters# Iterate through linesforlineinopen('myfile.txt'):
print(line, end='')
# Reset positionf.seek(0) # Go to beginningf.tell() # Current position
Writing Files
f.write(string) # Write stringf.writelines(list) # Write list of stringsf.flush() # Force write to disk (buffering)f.seek(offset) # Change position for next operationf.truncate([size]) # Truncate to size
⚠️Note: Output files are buffered. Use flush() or close() to ensure data is written.
File Context Manager
# Safe pattern - auto-closesmyfile=open(r'~/data.txt', 'r')
try:
forlineinmyfile:
print(line, end=' ')
finally:
myfile.close() # Optional in Python (auto-closes), but good habit
File Conversion
# Python relies on conversion functions to read from fileslines=open('file.txt').readlines()
lines= [line.rstrip() forlineinlines] # Remove \n# int() ignores \nlin=open('d.txt', 'r')
s=lin.readline() # Returns '89\n'i=int(s) # 89 (ignores \n)
Pickle Module — Object Serialization
importpickle# Save objectD= {'a': 1, 'b': 2}
F=open('database', 'wb') # 'wb' required for picklepickle.dump(D, F)
F.close()
# Load objectF=open('database', 'rb')
E=pickle.load(F) # Automatically converts to dict
ifx<y:
print('less')
elifx>y:
print('greater')
else:
print('equal')
# Ternary expressionresult=value_if_trueifconditionelsevalue_if_falseA=YifxelseZ# Assign Y if x is true, else Z
break# Exit loop immediatelycontinue# Skip to next iterationpass# Do nothing (placeholder)
range() & zip()
range(10) # 0 to 9range(1, 11) # 1 to 10range(0, 20, 2) # 0, 2, 4, ..., 18 (step=2)# zip combines iterableslist(zip([1, 2], ['a', 'b'])) # [(1, 'a'), (2, 'b')]# In Python 3.0+, zip returns iterator; use list() to force
Boolean & Logic
# All objects have boolean value# False: empty objects, 0, None# True: non-empty objects, non-zero, any other value# and/or return actual values (not just True/False)result=XandY# Returns Y if X is True, else Xresult=XorY# Returns X if X is True, else Y# Example: default valuevalue=uservalueordefault_value# Conditional assignmentresult= (XandY) orZ# Y if X is true, else ZX=AorBorCorNone# First non-empty object# in operator for membership'p'inset('spam')
'ham'in ['eggs', 'spam', 'ham']
input() Function
# Get user input from consolereply=input('Enter text: ')
# Example: input loop with validationwhileTrue:
reply=input('Enter text:')
ifreply=='stop':
breakelifnotreply.isdigit():
print('bad'*8)
else:
print(int(reply) **2)
print('Bye')
# Get an iterator from an objectL= [1, 2, 3]
i=iter(L)
i.__next__() # Returns first element (Python 3)i.next() # Python 2# Manual iterationI=iter(L)
whileTrue:
try:
X=next(I)
exceptStopIteration:
breakprint(X**2)
# Single pass iteratorR=range(3)
I1=iter(R)
next(I1) # Works# range() itself is not an iteratorR=range(3)
next(R) # Error! range is iterable, not iterator
Modules & Packages
Import Basics
importmodule# Import modulefrommoduleimportname# Import specific namefrommoduleimport*# Import all (discouraged)importmoduleasm# Aliasfrommoduleimportnameasn# Alias specific
Module Search Path
1. Home directory of program
2. PYTHONPATH directories (if set)
3. Standard library directories
4. .pth file contents (in site-packages)
5. site-packages directory (third-party packages)
# Modules are imported once and cachedimportaa.x=99importa# a is not re-imported, x is still 99# Force reload (Python 3.4+)importimportlibimportlib.reload(a) # Re-execute a's code
Packages
mypackage/
__init__.py # Makes directory a package
module1.py
subpkg/
__init__.py
module2.py
__name__# Current module name (e.g., '__main__' for top-level)__file__# Module's filename__doc__# Module/function docstring__dict__# Namespace dictionary
Main Guard
if__name__=='__main__':
# Code only runs when executed directly, not importedtest_code()
Dynamic Imports
# Reload a module after code changesimportimportlibimportlib.reload(module_name)
# Note: Only works for Python modules, not C extensions
classMyClass:
class_var=0definstance_method(self):
pass@staticmethoddefstatic_method():
return'static'@classmethoddefclass_method(cls):
returncls.class_varMyClass.static_method() # Works without instanceMyClass.class_method() # Receives class, not instance
Slots — Memory Optimization — Python 2.2+
classLimited:
__slots__= ['name', 'age'] # Only these attributes allowedobj=Limited()
obj.name='Alice'# OKobj.job='dev'# AttributeError!
Iteration Support
getitem for indexing
classStepperIndex:
def__getitem__(self, i):
returnself.data[i]
X=StepperIndex()
X.data="spam"foriteminX:
print(item, end=' ') # s p a m
# __contains__ is preferred for "in" operatorclassMyClass:
def__contains__(self, item):
returniteminself.data# __iter__ is preferred for iteration# __getitem__ is fallback for both# Order of preference for "in": __contains__ > __iter__ > __getitem__
Attribute Access Interception
# __getattr__ called when attribute not found elsewhereclassEmpty:
def__getattr__(self, attrname):
ifattrname=='age':
return40else:
raiseAttributeError(attrname)
X=Empty()
X.age# 40X.name# AttributeError: name# __setattr__ called when setting attributes (WATCH FOR INFINITE LOOP!)classControl:
def__setattr__(self, attr, value):
ifattr=='age':
self.__dict__[attr] =value+10# Use __dict__ to avoid recursion!else:
raiseAttributeError(attr+" not allowed")
# __delattr__ is similar to __setattr__ (watch for infinite loop)
Right-side Operations
classadder:
def__add__(self, val):
returnself.val+valdef__radd__(self, val):
returnself.__add__(val)
# Or shorthand__radd__=__add__
# dir() - list all attributesdir(sys) # All attributes in sys module# __doc__ - access docstringclassMyClass:
"""This is my class"""passMyClass.__doc__# "This is my class"# help() - display documentationhelp(MyClass)
Decorators
Function Decorators Basics
# Decorator is a callable that returns a callabledefdecorator(func):
defwrapper(*args, **kwargs):
print('before')
result=func(*args, **kwargs)
print('after')
returnresultreturnwrapper@decoratordefmy_func():
pass# Equivalent to: my_func = decorator(my_func)
Class Decorators
# Using a class to wrap functionsclassdecorator:
def__init__(self, func):
self.func=funcdef__call__(self, *args):
# Do something with self.func and argsreturnself.func(*args)
@decoratordeffunc(arg):
# do somethingpass
classStudent(object):
@propertydefscore(self):
returnself._score@score.setterdefscore(self, value):
ifnotisinstance(value, int):
raiseValueError("score must be an integer")
ifvalue<0orvalue>100:
raiseValueError("score must between 0-100")
self._score=value
importweakref# Weak references don't prevent object reclamation# Useful for caches of large objectsweakref.ref(obj)
Advanced Iteration (itertools)
Module Overview
importitertools# Python 2: many functions return lists# Python 3: most return iterators (using itertools!)
Functions
accumulate(iterable[, func]) — Accumulated sums
# Returns accumulated sums or results of other binary functions# If func supplied, should be function of two arguments# Roughly equivalent to:defaccumulate(iterable, func=operator.add):
it=iter(iterable)
try:
total=next(it)
exceptStopIteration:
returnyieldtotalforelementinit:
total=func(total, element)
yieldtotal# Examplelist(itertools.accumulate([1, 2, 3, 4])) # [1, 3, 6, 10]
*chain(iterables) — Chain multiple iterables
# Returns elements from first iterable until exhausted, then next, etc.# Note: argument is *iterable (multiple args), not single list!itertools.chain('abc', 'def') # a, b, c, d, e, f# WON'T work: itertools.chain(['abc', 'def'])# Use itertools.chain.from_iterable() insteadforiteminitertools.chain([1, 2], [3, 4]):
print(item) # 1, 2, 3, 4
combinations(iterable, r) — r-length combinations
# Return r length subsequences of elements from input iterable# Without replacementitertools.combinations('ABCD', 2) # AB AC AD BC BD CDitertools.combinations([1, 2, 3], 2) # (1,2), (1,3), (2,3)
combinations_with_replacement(iterable, r) — Combinations with replacement
# Return r length subsequences allowing individual elements repeateditertools.combinations_with_replacement('ABC', 2) # AA AB AC BB BC CC
# Return successive r length permutations of elements in iterableitertools.permutations('ABCD', 2) # AB AC AD BA BC BD CA CB CD DA DB DC
compress(data, selectors) — Filter with selector
# Make iterator that filters elements from data # returning only those with corresponding element in selectors that evaluates to True# Stops when either iterable exhausteditertools.compress('ABCDEF', [1, 0, 1, 0, 1, 1]) # A C E F# Roughly equivalent to:defcompress(data, selectors):
return (dford, sinzip(data, selectors) ifs)
count(start=0, step=1) — Infinite counter
# Make iterator that returns evenly spaced values starting with "start"# Often used as argument to map() to generate consecutive data points# Also used in zip() to add sequence numbersitertools.count(10) # 10, 11, 12, 13, ...itertools.count(2.5, 0.5) # 2.5, 3.0, 3.5, ...
cycle(iterable) — Repeat indefinitely
# Make iterator returning elements from iterable and saving a copy# When iterable exhausted, return elements from saved copy# Repeats indefinitelyitertools.cycle('ABCD') # A B C D A B C D ...
dropwhile(predicate, iterable) — Drop until predicate false
# Make iterator that drops elements from iterable as long as predicate is true# Afterwards, returns every element# Note: iterator doesn't produce output until predicate first becomes falseitertools.dropwhile(lambdax: x<5, [1, 4, 6, 4, 1]) # 6, 4, 1
filterfalse(predicate, iterable) — Filter false elements
# Make iterator that filters elements from iterable # returning only those for which predicate is false# If predicate is None, return items that are falseitertools.filterfalse(lambdax: x%2, range(10)) # 0 2 4 6 8
groupby(iterable, key=None) — Group consecutive items
# Make iterator that returns consecutive keys and groups# key is function computing key value for each element# Similar to Unix "uniq"
[kfork, ginitertools.groupby('AAAABBBCCAABBB')] # A B C A B
[[k, list(g)] fork, ginitertools.groupby('AAAABBBCCD')] # [['A', 'AAAA'], ...]# Returns groupby object with (key, group_iterator) tuples
# Returns selected elements from the iterableitertools.islice('ABCDEFG', 2) # A, Bitertools.islice('ABCDEFG', 2, 4) # C, Ditertools.islice('ABCDEFG', 2, None) # C, D, E, F, Gitertools.islice('ABCDEFG', 0, None, 2) # A, C, E, G
*product(iterables, repeat=1) — Cartesian product
# Cartesian product of input iterables# Roughly equivalent to: (x,y) for x in A for y in Bitertools.product('ABCD', 'xy') # Ax Ay Bx By Cx Cy Dx Dyitertools.product(range(2), repeat=3) # 000 001 010 011 100 101 110 111
repeat(object[, times]) — Repeat forever or n times
# Make iterator that returns object over and over again# Repeats indefinitely unless times argument is specifieditertools.repeat('A', 3) # A, A, Aitertools.repeat('A') # A, A, A, A, ... (infinite)
# Make iterator that computes function using arguments obtained from iterable# Used instead of map() when argument parameters already grouped in tuples# Distinction: function(a, b) vs function(*c)itertools.starmap(pow, [(2, 5), (3, 2), (10, 3)]) # 32 9 1000
takewhile(predicate, iterable) — Take until predicate false
# Make iterator that returns elements as long as predicate is true# Once predicate becomes false, we stopitertools.takewhile(lambdax: x<5, [1, 4, 6, 4, 1]) # 1 4
tee(iterable, n=2) — Independent iterators
# Return n independent iterators (in a tuple) from a single iterablec, d=itertools.tee([1, 2, 3], 2)
# Then c and d can iterate through list independently
*zip_longest(iterables, fillvalue=None) — Zip with fill
# Make iterator that aggregates elements from iterables# If iterables are uneven length, missing values filled with fillvalue# Iteration continues until longest iterable exhausteditertools.zip_longest('abcd', 'xy', fillvalue='-') # ax by c- d-
fromcollectionsimportdequed=deque([1, 2, 3])
d.append(4) # Add to rightd.appendleft(0) # Add to leftd.pop() # Remove from rightd.popleft() # Remove from leftd.extend([4, 5, 6]) # Extend rightd.extendleft([...]) # Extend leftd.rotate(n=1) # Rotate n steps rightd.rotate(-1) # Rotate leftd.count(x) # Count occurrencesd.remove(value) # Remove first occurrenced.clear() # Clear alld.reverse() # Reverse in-place# Thread-safe, memory efficient, O(1) operations on both ends
Counter — Tally occurrences
fromcollectionsimportCountercnt=Counter()
forwordin ['red', 'blue', 'red', 'green', 'blue', 'blue']:
cnt[word] +=1cnt# Counter({'blue': 3, 'red': 2, 'green': 1})# Methodscnt.elements() # Iterator over elements repeating eachcnt.most_common([n]) # n most common elements and countscnt.subtract([iterable]) # Subtract countscnt.update([iterable]) # Add counts
OrderedDict — Maintain insertion order
fromcollectionsimportOrderedDictD=OrderedDict([('z', 1), ('a', 2), ('b', 3)])
# Remembers order of element insertionD.popitem(last=True) # Return and remove specified key# last=True: remove last (LIFO), last=False: remove first (FIFO)
defaultdict — Auto-create missing values
fromcollectionsimportdefaultdict# Automatically creates values for missing keysD=defaultdict(list)
D['key'].append(1) # Works even if 'key' doesn't exist# Example: count words grouped by colors= [('yellow', 1), ('blue', 2), ('yellow', 3)]
d=defaultdict(list)
fork, vins:
d[k].append(v)
# d = {'yellow': [1, 3], 'blue': [2]}
Interactive Python (IPython & Jupyter)
IPython — Enhanced Python Interpreter
# Tab completion# Type and press Tab to complete names# Introspection with ?obj? # Display info about objectfunction? # Show docstring and signature
Magic Commands
# Magic commands prefixed with %%timeitstatement# Time execution of statement%timestatement# Report execution time of single statement%debug# Activate interactive debugger%pdb# Inspect stack frames on exception%pwd# Show current working directory%paste# Execute code from clipboard%cpaste# Prompt for code to paste and execute%quickref# Quick reference card%magic# Display all magic commands%hist# Print command input history%reset# Delete all variables%pageOBJECT# Pretty-print object through pager%prunstatement# Profile code with cProfile%who, %whos# Display variables in namespace%xdelvariable# Delete variable and clear references%matplotlib# Configure matplotlib integration%load# Load code from file%runfilename.py# Run Python script in IPython session
Jupyter Notebook
# Browser-based interactive Python
# Similar features to IPython
# Cell-based execution
# Rich output (plots, tables, etc.)
Scientific Computing
SciPy — Scientific Python
fromscipyimportintegrate, linalg, optimize, signal, sparse, special, stats# scipy.integrate - numerical integration, ODE solvers# scipy.linalg - linear algebra (extends numpy.linalg)# scipy.optimize - function optimizers, root finding# scipy.signal - signal processing# scipy.sparse - sparse matrices, sparse linear system solvers# scipy.special - special math functions (SPECFUN Fortran library wrapper)# scipy.stats - probability distributions, statistical tests
# Dictionary is much faster for membership testing# Use dict for fast lookups, not lists# Slowifxin [1, 2, 3, 4, 5, ...]:
pass# Fastifxin {1, 2, 3, 4, 5, ...}:
pass
LEGB Scope Rule
# Local → Enclosing → Global → Built-in# Use global to modify module-level variables# Use nonlocal (Python 3+) to modify enclosing function variables
Comprehension Order (Inner Loop on Right)
# Inner loop is on the RIGHT
[x+yforxin'abc'foryin'lmn']
# Equivalent to:result= []
forxin'abc':
foryin'lmn':
result.append(x+y)
Exception Handling Best Practices
# GOOD: catch specific exceptionstry:
num=int(reply)
exceptValueError:
print('Invalid number')
except: # Only if absolutely necessarypasselse:
print(num**2) # Runs if no exception# Don't use bare except unless absolutely necessary