Practice Flashcards
Reverse list
.reverse() in place, only for list
reversed() returns iterator
(if the input list changes iterator sees it)
[::-1] reversed copy, slow
Sequence Functions
len()
min()
max()
Functions that return iterator
reversed(), enumerate(), zip(), map(), filter()
Generator Usage
infinite sequence
Map
map(function, iterables)
transformation function
lambda function (don’t use!)
Filter
map(function, iterable)
map(None, iterable) True elements
lambda function (don’t use!)
Generator expression without ()
list(square(x) for x in numbers)
Sum
sum(iterable, start)
start = 0
can’t sum strings
Zip
zip(*iterables, strict=False)
strict=True raises ValueError if iterables have different length
dict(zip(keys, values))
Enumerate
enumerate(iterable, start=0)
Dictionary update()
dict.update(iterable or kwargs)
iterable: dict, iterable of tuples etc.
Sort
sort(*, key=None, reverse=False)
list.sort()
Max, Min
max(iterable, *, key=None)
max(iterable, *, default, key=None)
max(arg1, arg2, *args, key=None)
All, Any
all(iterable)
True if iterable is empty
any(iterable)
False if iterable is empty
Is Instance
isinstance(object, classinfo)
classinfo - type, tuple of types
Sorted
sorted(iterable, /, *, key=None, reverse=False)
returns a list
Dictionary Creation
- dict(dict1)
- dict(iterable of (key, value))
- merge: dict1 | dict2
- merge into a literal: {…, **dict1, …}
Is Subclass
issubclass(class, classinfo)
classinfo - class, tuple of classes
is class a subclass of classinfo
Size
import sys sys.getsizeof(obj)
Closure Usage
- function factories
- callbacks
- data encapsulation
- decorators
- memoization
Raw String Literal
r'<string>'
treats backlslashes as literal characters
Repr
repr(object)
returns a string containing a printable representation of an object
__repr__()
Import
import module
import module as name
from module import var1, var2
from module import var1 as name1, var2 as name2
Add
x = x + 1 – .__add__()
x += 1 – .__iadd__()
NamedTuple
namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
returns a new tuple subclass named typename
filednames – ['x, 'y']
or 'x y'
or 'x, y'
from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(11, y=22) print(p.x, p[1])
._fields
._make(iterable)
._asdict()
._replace(**kwargs)
Callable
callable(object)
True if object appears callable, False if not