Python Comparison Tables

Quick reference: side-by-side comparisons of Python concepts

List VS Tuple

Feature List Tuple
Syntax [1, 2, 3] (1, 2, 3)
Mutability Mutable (can change) Immutable (fixed)
Performance Slower Faster (fixed size)
Memory More memory Less memory
Methods append, insert, remove, pop, sort, etc. count, index only
Use Case When data needs modification When data should stay constant
Dictionary Key Cannot be used Can be used (hashable)
Iteration Speed Slightly slower Faster iteration
Built-in Functions sort(), reverse(), append() count(), index() only
Nesting Can contain any type Can contain any type
Creation list() or [] tuple() or ()

List VS Set VS Dictionary

Feature List Set Dictionary
Syntax [1, 2, 3] {1, 2, 3} {"a": 1}
Ordered Yes No Yes (Python 3.7+)
Duplicates Allowed Not allowed Keys: No, Values: Yes
Indexing lst[0] Not supported d["key"]
Mutable Yes Yes Yes
Use Case Ordered collection Unique items, math sets Key-value mapping
Search Speed O(n) - slow O(1) - fast O(1) - fast
Memory Usage Moderate Higher (hash table) Higher (hash table)
Empty Creation [] set() (not {}) {}
Comprehension [x for x in...] {x for x in...} {k:v for...}

for Loop VS while Loop

Feature for Loop while Loop
Syntax for i in range(5): while condition:
Iterations Known/definite Unknown/indefinite
Control Iterates over sequence Based on condition
Infinite Loop Risk Low (fixed iterations) High (if condition never False)
Best For Lists, strings, ranges User input, unknown end
Example Use Print 1 to 10 Keep asking until valid input
else Clause Supported Supported
break/continue Supported Supported
Recommended More Pythonic When needed

== (Equality) VS is (Identity)

Feature == (Equality) is (Identity)
Compares Values Memory location (same object)
Example a == b → True if same value a is b → True if same object
Use Case Compare content Check if None, singleton
Example:
a = [1, 2]
b = [1, 2]
a == bTrue (same values)
a is bFalse (different objects)
Best Practice: Use is only with None: if x is None:

Mutable VS Immutable

Feature Mutable Immutable
Definition Can be changed after creation Cannot be changed after creation
Data Types list, dict, set int, float, str, tuple, frozenset
Memory Same ID when modified New object created on change
Example lst[0] = 10 s[0] = 'H' ✗ Error
Dict Key Cannot be key Can be key
Thread Safety Not safe Safe

*args VS **kwargs

Feature *args **kwargs
Full Form Arguments Keyword Arguments
Type Tuple Dictionary
Usage Variable positional args Variable keyword args
Syntax def func(*args): def func(**kwargs):
Call func(1, 2, 3) func(a=1, b=2)
Access for arg in args: for key, val in kwargs.items():
Combined: def func(a, b, *args, **kwargs):

Common String Methods

Method Description Example Result
upper() Uppercase "hello".upper() "HELLO"
lower() Lowercase "HELLO".lower() "hello"
strip() Remove whitespace " hi ".strip() "hi"
split() Split to list "a,b,c".split(",") ['a','b','c']
join() Join list to string ",".join(['a','b']) "a,b"
replace() Replace substring "hi".replace("i","ey") "hey"
find() Find index (-1 if not found) "hello".find("l") 2
count() Count occurrences "hello".count("l") 2

File Reading Methods

Method Returns Example Output
read() Entire file as single string "Line1\nLine2\nLine3"
read(n) First n characters "Line" (n=4)
readline() One line at a time "Line1\n"
readlines() List of all lines ["Line1\n", "Line2\n", "Line3"]
Best Practice: For large files, iterate directly:
for line in file: (memory efficient)

break VS continue VS pass

Statement Action Use Case
break Exit loop immediately Stop when condition met
continue Skip to next iteration Skip certain items
pass Do nothing (placeholder) Empty function/class body

List: append VS extend VS insert

Method Action Example Result
append(x) Add x as single element [1,2].append([3,4]) [1, 2, [3, 4]]
extend(x) Add each element of x [1,2].extend([3,4]) [1, 2, 3, 4]
insert(i, x) Add x at index i [1,3].insert(1, 2) [1, 2, 3]

Local VS Global Variables

Feature Local Variable Global Variable
Scope Inside function only Throughout the program
Declaration Inside function Outside all functions
Lifetime Until function ends Until program ends
Access Only within function Anywhere (use global keyword to modify)
Memory Stack memory Heap memory
Best Practice Preferred (encapsulation) Use sparingly

Shallow Copy VS Deep Copy

Feature Shallow Copy Deep Copy
Definition Copies object, references nested objects Copies object and all nested objects recursively
Method copy.copy() or list.copy() copy.deepcopy()
Nested Objects Shared with original Independent copies
Speed Faster Slower
Memory Less memory More memory
Use Case Simple/flat objects Nested/complex objects
Example:
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)

Function VS Method

Feature Function Method
Definition Independent block of code Function associated with object
Called Using function_name() object.method_name()
First Parameter Explicit arguments only self (implicit reference)
Defined In Module/script level Inside a class
Example len(my_list) my_list.append(5)
Access to Object Data No (unless passed) Yes (via self)

remove() VS del VS pop()

Feature remove() del pop()
Removes By Value Index Index
Returns Value No No Yes
Multiple Items First occurrence only Can use slicing One at a time
Syntax list.remove(5) del list[0] list.pop(0)
Default N/A N/A Last element (-1)
Error If Not Found ValueError IndexError IndexError

range() VS xrange() (Python 2/3)

Feature range() (Python 3) xrange() (Python 2)
Return Type range object (iterable) xrange object (generator)
Memory Memory efficient Memory efficient
Python 2 Returns list (memory heavy) Generator-like object
Python 3 Behaves like xrange Removed
Indexing Supported Supported

List VS NumPy Array

Feature Python List NumPy Array
Data Types Heterogeneous (mixed) Homogeneous (same type)
Memory More memory Less memory (contiguous)
Speed Slower Much faster (vectorized)
Operations Element by element Broadcasting supported
Import Needed Built-in import numpy as np
Use Case General purpose Scientific computing, ML
Multi-dimensional Nested lists (complex) Native support (ndarray)

Module VS Package VS Library

Feature Module Package Library
Definition Single .py file Directory with __init__.py Collection of packages
Contains Functions, classes, variables Multiple modules Multiple packages
Import import math import package.module import numpy
Example math.py, random.py urllib/, json/ NumPy, Pandas, Django
__init__.py Not needed Required (can be empty) Has init in packages

input() VS raw_input() (Python 2/3)

Feature input() Python 3 input() Python 2 raw_input() Python 2
Returns String Evaluated expression String
Safety Safe Unsafe (eval) Safe
Python 3 Standard input method N/A Removed
Convert to int int(input()) Automatic if typed int(raw_input())

Recursion VS Iteration

Feature Recursion Iteration
Definition Function calls itself Loop repeats code
Termination Base case Condition becomes False
Memory Uses stack (can overflow) Less memory
Speed Slower (function calls) Faster
Code Often simpler, elegant Can be complex
Use Case Trees, factorial, Fibonacci Most general loops
Stack Limit ~1000 calls default No limit