Sequences · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. What does this print?
grid = [[0]] * 3
grid[0].append(1)
print(grid)
2. What does this print?
l = [0, 1, 2, 3, 4, 5]
print(l[3:-1:-1])
3. What does this print?
t = (1, 2, 3)
print(t[:] is t, tuple(t) is t, list(t) is t)
4. What does this print?
a = [[1], [2]]
b = a.copy()
b[0].append(9)
b[1] = [0]
print(a)
5. What does this print?
a = [1, 2]
b = a
a += [3]
a = a + [4]
print(b)
6. What does this print?
l = [1, 2, 3, 4, 5]
l[1:1] = 'xy'
print(l)
7. What happens here?
l = [1, 2, 3, 4, 5]
l[::2] = [0, 0]
8. What does this print?
t = 'bb', 'a', 'cc', 'd'
print(sorted(t, key=len))
9. What does this print?
l = [3, 1, 2]
l = l.sort()
print(l)
10. What does this print?
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])
11. A class defines only __getitem__, which returns index * 10 for any integer and never raises. What happens with for x in obj: ...?
12. What is the result of running this code?
t = ([1], 'x')
try:
    t[0] += [2]
except TypeError:
    print('error', t)

Coding exercises

Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.

Exercise 1: Split a sequence into chunks

Write chunked(seq, size) that splits any sequence into consecutive pieces of length size (the last piece may be shorter) and returns them as a list.

Each piece must have the same type as seq: chunking a string gives strings, chunking a tuple gives tuples. If size is less than 1, raise ValueError.

python chunked('abcdefg', 3) # ['abc', 'def', 'g'] chunked((1, 2, 3, 4), 2) # [(1, 2), (3, 4)] chunked([], 2) # []

Hints (2)
  1. Slicing always returns the same type as the sequence being sliced, and out-of-range bounds are clipped.
  2. range(0, len(seq), size) gives the start index of every chunk.
Show a solution
def chunked(seq, size):
    if size < 1:
        raise ValueError('size must be at least 1')
    return [seq[i:i + size] for i in range(0, len(seq), size)]

Exercise 2: A grid without aliases

make_grid(rows, cols, fill) should return a list of rows lists, each containing cols copies of fill. The current version has a classic bug: changing one cell changes a whole column.

Fix it so that every row is an independent list.

Hints (2)
  1. [row] * rows repeats a reference to one row. You need a new row object for each repetition.
  2. A list comprehension evaluates its expression once per iteration, creating a fresh list each time.
Show a solution
def make_grid(rows, cols, fill=0):
    return [[fill] * cols for _ in range(rows)]

Exercise 3: A lazy sequence of squares

Write a class Squares(n) that behaves like the read-only sequence 0, 1, 4, 9, ..., (n-1)**2 without storing the values.

It must support:

- len(sq) returning n - indexing with positive and negative integers, raising IndexError when out of range - slicing (including steps and negative steps), returning a list of squares - iteration, in and reversed() (these follow automatically if the above is right)

Hints (2)
  1. Check isinstance(s, slice) first. range(*s.indices(len(self))) gives exactly the positions the slice selects.
  2. For an integer, add n to a negative index, then raise IndexError if it's still outside 0 .. n-1. Without that, iteration never stops.
Show a solution
class Squares:
    def __init__(self, n):
        self._n = n

    def __len__(self):
        return self._n

    def __getitem__(self, s):
        if isinstance(s, slice):
            return [i ** 2 for i in range(*s.indices(self._n))]
        if s < 0:
            s += self._n
        if s < 0 or s >= self._n:
            raise IndexError('Squares index out of range')
        return s ** 2

Exercise 4: Sort by several criteria

Each record is a tuple (name, department, salary). Write sort_staff(records) that returns a new list ordered:

1. by department, alphabetically; 2. within a department, by salary, highest first; 3. when salaries tie too, by name, alphabetically.

The input must not be modified (it might be a tuple, or a list someone else is using).

Hints (2)
  1. sorted() accepts any iterable and returns a new list; list.sort() mutates (and tuples don't have it).
  2. A key that returns a tuple sorts by its first element, then the second, and so on. Negate the salary to make just that part descending.
Show a solution
def sort_staff(records):
    return sorted(records, key=lambda r: (r[1], -r[2], r[0]))