Based mostly on the Tutorial, section 5
Summary of list methods:
→ Example: lists-1.txt
s.append(value) # push s.pop() # pop uses the default last index position
→ Example: stacks.txt
s.append(value) # enqueue s.pop(0) # dequeue
→ Example: queues.txt
filter(func, seq)map(func/1, seq1)map(func/2, seq1, seq2)map(func/n, seq1, ..., seqn)reduce(func/2, seq, [init])functools module.)
reduce(f, []) is an error.reduce(f, [a]) → areduce(f, [a, b]) → f(a, b)reduce(f, [a, b, c]) → f(f(a, b), c)reduce(f, [], a) → areduce(f, [b], a) → f(a, b)reduce(f, [b, c], a) → f(f(a, b), c)reduce(f, [b, c, d], a) → f(f(f(a, b), c), d)sum(seq)reduce(lambda x, y: x + y, seq, 0)
→ Example: functions.py
→ Example: functional-1.txt
Equivalent to map or filter expressions (but not reduce), without an explicit function and more convenient syntax.
A list comprehension requires at least one for clause, which may be followed by 0 or more for or if clauses.:
Note: use the zip function for mapping with >1 argument.
[x + y for x, y in zip(alist, blist)] [x + y for x in alist for y in blist] # different
→ Example: functional-2.txt
Deleting:
del(alist[index])
Sequences include strings, lists, tuples.
With a non-empty tuple, the ()'s are optional in input, but always printed in output.
A trailing comma is required for a singleton tuple: (5,) or 5, and is allowed for longer tuples.
t = 1, 2 # equivalent t = 1, 2, # equiv., final comma optional e = () # empty tuple s1 = (5, ) # comma required s1 = 5, # equiv., comma required u = 1, 3, 5 # packing a, b, c = u # unpacking
Sequences can be packed into a variable,
x = seq
or unpacked into a sequence of variables
x, y, z = seq
Multiple assignment is just unpacking and packing together.
Packing/unpacking work with any sequence types.
Use the tuple function to convert other sequences to tuples.
tuple(seq)
→ Example: tuples.txt
Sets can be created from any sequence type (list, tuple, string). They are unordered collections without duplicates, and support set operations:
set([a, b, ...])x in sr - sr | sr & sr ^ s == (r | s) - (r & s)→ Example: sets.txt
d = {}d.keys()d.values()d.items()d.has_key(k)k in dd[k]d[k] = 'maurice'del d[k]→ Example: dict.txt
for key, value in dict.items(): ... for index, value in enumerate(seq): ... for x, y in zip(seqx, seqy): ... # paired values from each sequence
(skip)
(1, 2, 3) < (1, 2, 4) # because 3 < 4 (1, 2) < (1, 2, 3) # because (1, 2) has fewer elements (1, 2) == (1, 2)