You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
s[start:stop:step]
# Defaults:# start=0, stop=len(s), step=1# Common patterns:s[:] # full copys[::-1] # reverseds[::2] # every other elements[-3:] # last 3s[:-3] # all but last 3s[1:-1] # all but first and last# Named slices:FIELD=slice(0, 5)
data[FIELD] # equivalent to data[0:5]
array.array Type Codes
Code
C Type
Python Type
Size
'b'
signed char
int
1 byte
'B'
unsigned char
int
1 byte
'h'
signed short
int
2 bytes
'H'
unsigned short
int
2 bytes
'i'
signed int
int
2+ bytes
'l'
signed long
int
4+ bytes
'f'
float
float
4 bytes
'd'
double
float
8 bytes
Sorting Key Functions
# By attributesorted(objects, key=lambdao: o.name)
# By multiple fields (tuple comparison)sorted(objects, key=lambdao: (o.category, o.name))
# Using operator.attrgetter (faster than lambda)fromoperatorimportattrgettersorted(objects, key=attrgetter("category", "name"))
# Using operator.itemgetter for tuples/dictsfromoperatorimportitemgettersorted(records, key=itemgetter(1, 0)) # sort by [1] then [0]# Reversesorted(items, reverse=True)
# Stable: equal elements preserve original order
deque Maxlen — Ring Buffer Pattern
fromcollectionsimportdeque# Fixed-size sliding window:window=deque(maxlen=5)
foritemindata_stream:
window.append(item) # Old items auto-evicted when maxlen is reached# window always contains the last 5 items
Vocabulary
Term
Definition
Container sequence
Stores references to Python objects (any type)
Flat sequence
Stores C values directly (single type, memory-efficient)