Review of Python — Part 1C

Based mostly on the Tutorial, section 5

5 Data Collections

5.1 More on Lists

Summary of list methods:

mutating:
append(value), extend(anotherlist), insert(index, value), remove(value), sort(), reverse(), pop([index])
non-mutating:
index(value), count(value)

→ Example: lists-1.txt

5.1.1. Lists as stacks

s.append(value) # push
s.pop()         # pop uses the default last index position

→ Example: stacks.txt

5.1.2 Lists as queues

s.append(value) # enqueue
s.pop(0)    # dequeue

→ Example: queues.txt

5.1.3 Functional tools for lists [and other sequences]

filter(func, seq)
Returns the sequence consisting of elements x of seq for which func(x) is true.
Returns same sequence type as seq.
map(func/1, seq1)
map(func/2, seq1, seq2)
...
map(func/n, seq1, ..., seqn)
Applies a function of n arguments to corresponding elements of each of the n sequences: all the first elements, all the second elements, etc.
Always returns a list, regardless of the sequence type.
reduce(func/2, seq, [init])
Functional accumulator, applies func/2 to all the elements of seq in turn. First argument is the accumulated value, initially init; second argument is the current element. (This was a builtin function of Python 2, but in Python 3 must be imported from the functools module.)
Without an initial value:
reduce(f, []) is an error.
reduce(f, [a]) → a
reduce(f, [a, b]) → f(a, b)
reduce(f, [a, b, c]) → f(f(a, b), c)
etc.
With an initial value:
reduce(f, [], a) → a
reduce(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)
etc.
sum(seq)
Special case, more efficient than reduce(lambda x, y: x + y, seq, 0)

→ Example: functions.py

→ Example: functional-1.txt

5.1.4 List comprehensions

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.:

for == map
if == filter

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

5.2 The del statement

Deleting:

del(alist[index])

5.3 Tuples and sequences

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

5.4 Sets

Sets can be created from any sequence type (list, tuple, string). They are unordered collections without duplicates, and support set operations:

create:
set([a, b, ...])
membership:
x in s
difference:
r - s
union:
r | s
intersection:
r & s
symmetric difference:
r ^ s == (r | s) - (r & s)

→ Example: sets.txt

5.5 Dictionaries

Empty dictionary:
d = {}
List of keys:
d.keys()
List of values:
d.values()
List of key, value tuples:
d.items()
Does it have a key?
d.has_key(k)
k in d
Value associated with key k:
d[k]
Set or change the value:
d[k] = 'maurice'
Delete the value:
del d[k]

→ Example: dict.txt

5.6 Looping techniques

for key, value in dict.items(): ...

for index, value in enumerate(seq): ...

for x, y in zip(seqx, seqy): ... # paired values from each sequence

5.7 More on conditions

(skip)

5.8 Comparing sequences and other types

(1, 2, 3) < (1, 2, 4) # because 3 < 4
(1, 2) < (1, 2, 3)    # because (1, 2) has fewer elements
(1, 2) == (1, 2)

Suggested Exercises

  1. Write a function which reads a series of lines from the keyboard, terminated by an empty line. The function accumulates the lines as a list of strings, and returns the list. Hint: start with []; use append.
  2. (New in version 5) Do the same, recursively, and without mutating any variables (so, without using append). Hint: [] is the base case value; use + to concatenate lists.
  3. (firsts) Write a function that finds the first character of each string in its list argument, using map. The function returns a list of the first characters.
  4. (shorts) Write a function that finds the strings of length 4 or less in its list argument, using filter. The function returns the list of short strings.
  5. Redo "firsts", using a list comprehension.
  6. Redo "shorts", using a list comprehension.
  7. Combine "firsts" and "shorts", using a list comprehension. I.e., the function takes a list of strings as argument; it returns a list of the first characters of those strings which have length 4 or less.

→ Solutions