Pythonic Programming
by
Thomas Heinrichsdobler
5.0 stars - 1 reviews
Pythonic Programming
Syntax
use parenthesis for long-line
wrapping
use r"C:\temp.txt" for raw strings
Backslashes not interpreted
as escapes
ideal for Windows file paths
use "".join(list) to join a list of strings
add spaces or commas as
needed, " ".join(list), ", ".join(list)
use generator functions, "".join(fn(i) for i in items)
use collections.defaultdict() to create
dictionaries with default factory
functions
use locals() for named string
formatting
Use a list comprehension when a
computed list is the desired end
result.
[n ** 2 for n in range(10) if n % 2]
all values calculated at once
greedy evaluation
Use a generator expression
when the computed list is
just an intermediate step.
values calculated as needed
use lists instead of
concatenating strings using the
"+=" operator.
huge memory saver
huge speed improvement
can be joined before output
Links