Functional 100 Python functions

admin
By -
0



if you need this all as pdf just drop comment "need pdf" below.

Concept

Syntax Example

Use Cases

Example

Enumerate

enumerate(data)

Indexing, row tracking, progress logs.

Numbering search results in a UI list.

Map

map(int, strings)

Batch casting, scrubbing, normalization.

Converting API string prices into floats.

Filter

filter(func, data)

Pruning data, permission checks, exclusion.

Removing "Inactive" users from a mailing list.

Lambda

lambda x: x.id

Sort keys, inline logic, callbacks.

Sorting user objects by created_at.

Zip

zip(list_a, list_b)

Pairing data, building dicts, merging.

Mapping CSV headers to row data.

Zip Strict

zip(a, b, strict=True)

Safe merging, length validation.

Ensuring emails and user_ids match in size.

Any

any([c1, c2])

Permission checks, "at least one" logic.

Checking if a user has any required role.

All

all([c1, c2])

Bulk validation, "everything" checks.

Verifying all required form fields are filled.

List Comp

[x.id for x in data]

Extracting IDs, mapping, list creation.

Getting clean IDs from a database result.

Dict Comp

{x.id: x for x in l}

ID mapping, swapping keys/values.

Creating a fast id -> object lookup map.

Set Comp

{x.tag for x in l}

Unique extraction, membership testing.

Getting unique categories from 1,000 posts.

Gen Exp

(x for x in huge)

Memory efficiency, lazy streaming.

Processing 1M logs without crashing RAM.

Walrus

if (u := get()):

Inline assign, reducing redundant calls.

Fetching a record and checking it in one line.

Sorted

sorted(l, key=f)

Custom ordering, priority levels.

Sorting products by "Price" then "Rating".

Reversed

reversed(data)

Backwards iteration, recent-first logic.

Showing recent notifications at the top.

Sum

sum(iterable)

Totals, merging lists, counting.

Calculating "Total Cart Value" at checkout.

Min / Max

max(l, key=f)

Finding extremes, bounds checking.

Finding the "Highest Rated" item in a list.

Next

next(it, default)

First-match-only, manual stepping.

Fetching the "First Available" worker.

Iter (Basic)

iter(data)

Converting to stream, manual control.

Stepping through a data buffer chunk by chunk.

Iter Sentinel

iter(f, stop)

Breaking on specific value/stream end.

Reading a file until an "END" line is found.

Star Unpack

a, *b, c = list

Head/Tail logic, variable processing.

Splitting a command into action and params.

Nested Unpack

(a, b), c = data

Complex structure extraction.

Unpacking ((lat, lon), city_name) pairs.

Inline If

x if cond else y

Ternary logic, UI label formatting.

Displaying "Paid" or "Pending" labels.

Callable

callable(obj)

Verifying executable status, safety.

Checking if a plugin attribute is a function.

Len

len(container)

Size checks, pagination, empty checks.

Checking if search results have any items.

Dir

dir(obj)

Introspection, discovery, debugging.

Finding all methods available on an object.

Slicing

l[start:stop:step]

Data windows, sampling, reversing.

Getting the "Recent 5" items from a list.

Frozenset

frozenset(l)

Immutable sets, hashable dict keys.

Using a group of tags as a cache dict key.

Set Ops

a | b, a & b

Union/Intersection, commonalities.

Finding "Mutual Friends" between users.

Format

format(v, '.2f')

Precise rounding, report padding.

Rounding tax to exactly 2 decimal places.

Join

" ".join(list)

Building messages, joining paths.

Merging error messages into one string.

Range

range(n)

Lazy sequence generation, loops.

Generating page numbers for a web grid.

Isinstance

isinstance(o, t)

Inheritance-aware type verification.

Checking if data is a BaseModel.

Issubclass

issubclass(A, B)

Checking interface compliance.

Verifying a Class inherits from a Mixin.

Globals

globals()

Dynamic variable access.

Fetching a Class by its string name.

Locals

locals()

Debugging local scope variables.

Inspecting variables during a crash log.

Abs

abs(n)

Distance math, normalization.

Calculating price differences.

Round

round(n, 2)

Formatting, cleaning float results.

Finalizing a total for a payment gateway.

Divmod

divmod(a, b)

Quotient/Remainder math, paging.

Calculating (total_pages, remainder).

Bool

bool(x)

Truthiness conversion, logic guards.

Forcing a "Truthiness" check on custom data.

Attribute Check

hasattr(o, 'a')

Dynamic property checking, safety.

Checking if an object has a .save() method.

Getattr

getattr(o, 'k')

Dynamic string-based access.

Accessing attributes using strings from JSON.

Setattr

setattr(o, 'k',v)

Dynamic object updates.

Mapping JSON fields to an object's state.

Delattr

delattr(o, 'k')

Removing dynamic attributes.

Cleaning up temporary properties on an object.

Vars

vars(obj)

Converting instances to dicts.

Dumping object data into a JSON response.

Id

id(obj)

Memory address verification.

Checking if two variables are the same object.

Hash

hash(obj)

Key generation, integrity.

Using a custom object as a dictionary key.

Type()

type(obj)

Strict type checking.

Verifying exact class (no inheritance).

In / Not In

x in container

Membership and exclusion logic.

Ensuring a "Username" is not already taken.

Multi-Assign

x, y = y, x

Variable swapping, clean init.

Swapping values without a temporary variable.

F-String Logic

f"{x + y}"

Evaluating math inside strings.

Building dynamic alert messages for users.

F-String Align

f"{x:<10}"

CLI table formatting, padding.

Creating aligned terminal reports.

Closure State

nonlocal count

Counter persistence in functions.

Creating a unique ID generator function.

Short-circuit

a or b

Default value setting.

name = input() or "Guest".

And logic

valid and save()

Conditional execution.

Saving a form only if validation passes.

Unpacking (*)

f(*args)

Dynamic function calling.

Passing a list of parameters to an API call.

Kwarg Unpack

f(**kwargs)

Dynamic setting injection.

Passing a dictionary of config to a class.

Set Union

s.union(o)

Merging unique datasets.

Combining two different subscriber lists.

Set Diff

s.difference(o)

Exclusion logic.

Finding users in list A but NOT in list B.

Pow

pow(b, e)

Exponential math.

Calculating growth rates or interest.

Truthy Empty

if not my_list:

Pythonic empty check.

Aborting if no search results are found.

Help

help(obj)

CLI Documentation.

Checking method usage in the terminal.

Ord / Chr

ord('A')

Character math/logic.

Creating simple custom text filters.

Bin/Hex/Oct

bin(n)

Numeric representation.

Creating flag-based permission strings.

Int(str, base)

int('10', 2)

Parsing different number formats.

Converting binary/hex strings to numbers.

Complex

complex(r, i)

Vector calculations.

Handling coordinates in a 2D grid.

Repr vs Str

repr(o) / str(o)

Debug vs End-user view.

Printing detailed logs vs UI labels.

List(it)

list(map(...))

Consuming lazy streams.

Turning a lazy filter into a reusable list.

Tuple Literal

x = 1, 2

Implicit tuple creation.

Returning multiple values from a function.

Set intersection

a & b

Finding commonalities.

Finding "Common Followers" between users.

Set Symm Diff

a ^ b

Finding unique differences.

Finding items in A or B, but not both.

Is Disjoint

a.isdisjoint(b)

Overlap check.

Verifying two user groups have zero overlap.

Ellipsis

...

Placeholder logic.

Using ... as a "To-Do" in code.

Sorted reverse

sorted(l, rev=T)

Descending order.

Getting "Top 10" highest prices.

Slice step

l[::-1]

Reversing data.

Fast string reversal for UI effects.

Slice copy

l[:]

Shallow copying.

Creating a list copy to safely modify.

Format padding

format(x, '0>5')

Serial numbering.

Turning 7 into "00007" for IDs.

Bytearray

bytearray(data)

Buffer modification.

Editing raw image data in memory.

Memoryview

memoryview(obj)

Efficient binary slicing.

Handling large file chunks without RAM copy.

Globals get

globals()['x']

Safe dynamic variable lookup.

Fetching a global setting by string name.

Locals keys

x' in locals()

Variable existence check.

Verifying if a variable was defined in scope.

Comparison Chain

1 < x < 10

Range validation.

Checking if age is between 18 and 65.

Truthy check

bool(obj)

State verification.

Checking if an object has "Value".

Ascii

ascii(obj)

Log escaping.

Safe-printing strings with emojis to logs.

Compile

compile(str)

Dynamic code prep.

Pre-compiling user-input math formulas.

Eval

eval(str)

Result calculation.

Running a math calculation from a string.

Exec

exec(str)

Dynamic code execution.

Running dynamically generated scripts.

Object()

object()

Sentinel creation.

Creating a unique NOT_FOUND marker.

Property()

property(f)

Attribute calculation.

Creating a read-only field in a class.

Static Method

staticmethod(f)

Namespace grouping.

Adding a helper function inside a class.

Class Method

classmethod(f)

Alternative constructors.

User.from_email(address) logic.

Super()

super().func()

Parent delegation.

Adding setup logic to an inherited class.

Self

self.attr

Instance referencing.

Modifying a specific object's state.

Id check

id(a) == id(b)

Identity verification.

Ensuring two objects are the same in memory.

Iter next pair

(next(i), next(i))

Chunking data.

Processing a list in pairs of two.

F-string expr

f"{x.upper()}"

Formatting logic.

Converting names to uppercase in a string.

F-string debug

f"{x=}"

Quick variable logging.

Printing x=10 instantly for debugging.

Starred return

return *a, b

Multi-value merging.

Returning a list plus a flag from a function.

None check

if x is None:

Null safety.

Checking if an API call returned no data.

Builtins

__builtins__

Namespace inspection.

Accessing core functions programmatically.


s





Post a Comment

0Comments

Please Select Embedded Mode To show the Comment System.*