def by_chain(atoms):
    """Iterate over atoms by chain, returning a list of list of atoms."""
    chains = []
    current = []
    last = None
    for atom in atoms:
        if atom.chain != last:
            if len(current) != 0:
                chains.append(current)
            current = [atom]
            last = atom.chain
        else:
            current.append(atom)
    if len(current) != 0:
        chains.append(current)
    return chains