def by_residue(atoms):
    """Iterate over atoms by residue, returning a list of list of atoms."""
    residues = []
    current = []
    lastid = None
    lastname = None
    lastchain = None
    for atom in atoms:
        if atom.resid != lastid or atom.resname != lastname or \
                atom.chain != lastchain:
            if len(current) != 0:
                residues.append(current)
            current = [atom]
            lastid = atom.resid
            lastname = atom.resname
            lastchain = atom.chain
        else:
            current.append(atom)
    if len(current) != 0:
        residues.append(current)
    return residues