Imp-Standard Libraries

SI
Module / Topic
Common Methods / Classes / Techniques
Use Case / Description
Code Example (Short)

1

math

sqrt(), pow(), floor(), ceil(), factorial(), pi, log()

For mathematical operations like square root, power, rounding, constants

math.sqrt(16) → 4.0 math.ceil(2.3) → 3

2

collections.Counter

Counter(iterable)

Count frequency of elements in a list or string

Counter('apple') → {'p':2, 'a':1, 'l':1, 'e':1}

3

collections.defaultdict

defaultdict(list/int/set)

Provides default values for missing keys

d = defaultdict(int); d['x'] += 1 → {'x':1}

4

collections.namedtuple

namedtuple('Point', ['x', 'y'])

Lightweight object-like tuple with named fields

p = Point(1,2); p.x → 1

5

collections.deque

append(), appendleft(), pop(), popleft()

Fast and memory-efficient stack/queue

dq = deque([1,2]); dq.appendleft(0)

6

itertools.count()

count(start, step)

Infinite counter generator

for i in count(10, 2):

7

itertools.cycle()

cycle(iterable)

Repeats elements in a cycle

for i in cycle([1,2,3])

8

itertools.combinations

combinations(iterable, r)

Generate r-length combinations

list(combinations([1,2,3], 2)) → [(1,2), (1,3), (2,3)]

9

itertools.permutations

permutations(iterable, r)

Generate r-length permutations

list(permutations([1,2,3], 2)) → [(1,2), (1,3), (2,1), ...]

10

itertools.chain

chain(a, b, ...)

Flatten multiple iterables

list(chain([1,2], [3,4])) → [1,2,3,4]

11

String slicing

s[::-1], s[start:end:step]

Extract parts of string

'hello'[::-1] → 'olleh'

12

String methods

upper(), lower(), strip(), replace(), split(), join()

Clean and transform strings

'Hello'.lower() → 'hello' '-'.join(['a','b']) → 'a-b'

13

String formatting

f"{var}", .format()

Interpolating variables into strings

f"Hi {name}" or "Hi {}".format(name)

14

re (regex) (Optional)

findall(), sub(), search()

Pattern matching in strings

re.findall(r'\d+', 'abc123') → ['123']


SI
Module / Topic
Common Methods / Classes / Techniques
Use Case / Description
Code Example (Short)

1

datetime

datetime.now(), timedelta, strftime(), strptime()

Working with date and time, formatting, date arithmetic

datetime.now().strftime("%Y-%m-%d") → '2025-04-17'

2

os

os.listdir(), os.path.join(), os.remove(), os.getenv()

Interacting with the file system and environment variables

os.listdir('.') → ['file1.py', 'test.txt']

3

sys

sys.argv, sys.exit(), sys.path

Access to command-line args, Python path, and exit handling

sys.argv → ['script.py', 'arg1']

4

pathlib

Path('folder').exists(), Path.glob('*.txt')

Modern, object-oriented file and path handling

from pathlib import Path; Path('.').glob('*.py')

5

re

search(), match(), findall(), sub()

Regular expression for text search, validation, cleaning

re.findall(r'\d+', 'abc123') → ['123']

6

functools

lru_cache, partial, reduce()

Higher-order functions, caching, function composition

@lru_cache; reduce(lambda x,y:x+y, [1,2,3]) → 6

7

operator

itemgetter, attrgetter, add, mul

Functional alternatives for common operators (sorting, arithmetic)

sorted(lst, key=itemgetter(1))

8

typing

List, Dict, Union, Optional

Type hinting and static typing

def func(data: List[int]) → int:

9

enum

Enum, auto()

Create readable and fixed constants

class Color(Enum): RED = auto()

10

json

json.load(), json.dump(), json.loads(), json.dumps()

Parsing and serializing JSON data

json.loads('{"x":1}') → {'x': 1}

11

logging

basicConfig(), info(), warning(), error(), debug()

Better alternative to print for debugging

logging.info("Running script...")

12

random

random.random(), randint(), choice(), shuffle()

Generate random numbers, shuffle sequences

random.choice([1,2,3])

13

statistics

mean(), median(), stdev()

Perform basic statistical analysis

statistics.mean([1, 2, 3]) → 2

14

heapq

heapify(), heappush(), heappop()

Efficient min-heap queue operations

heapq.heappop([1,3,2]) → 1

15

time

time(), sleep(), perf_counter()

Benchmarking and adding delays

time.sleep(1); time.time()

16

uuid

uuid.uuid4()

Generate universally unique identifiers (UUID)

str(uuid.uuid4()) → 'a1b2c3...xyz'

17

pprint

pprint()

Pretty-printing complex data structures

pprint(data) for nested dicts

18

shutil

copy(), move(), rmtree()

File operations like copying and deleting folders

shutil.copy('a.txt', 'b.txt')

19

tempfile

NamedTemporaryFile(), TemporaryDirectory()

Create temporary files and directories

with tempfile.TemporaryDirectory() as tmp:

20

traceback

traceback.print_exc()

Print or log complete error stack trace

traceback.print_exc()

Last updated