__len__
, __getitem__
, __repr__
etc.. Often pronounced dunder xx), your objects can utilize built-in functions and syntax like len()
, []
, for ... in ...
and thus be considered Pythonic.len(xx)
over xx.len()
: Think of these functions as unary operators.list_a = [i + j for i in ... for j in ...]
for i in ...
part is the outer loop.xx(i + j for i in ... for j in ...)
()
vs []
. But under the hood it saves space by yielding item one by one so a full list is never constructed. Also it can be used to build many other containers.%
string formatting print('%s %s' % tup)
, passing function parameter f(*tup)
.*
dicussed below.a, *b, c = range(5)
and b
is [1, 2, 3]
. Only one *
prefix variable is allowed.collections.namedtuple
NamedTup._make(iterable)
. NamedTup(*iterable)
.._asdict()
return a collections.OrderedDict
[:3]
exclude the last item.f(a, ..., z)
and slice a[i:...]
. If a
is four dimentional, this is a shortcut for a[i, :, :, :]
. It is mostly used in Numpy.+
and *
and augmented assignment on sequencesmy_list = [[]] * 3
will result in a list with three references to the same inner list. List comprehension avoids this problem. [[] for i in range(3)]
.+=
and *=
will first try to use __iadd__
and fall back to __add__
and create a new object.list.sort
and sorted
list.sort
sorts inplace and returns None
.sorted
library function accepts any iterable object.reverse
bool and key
for the name of a function that produces sorting keys.