How to Iterate in PyMOL

Sometimes pointing-and-clicking just doesn’t cut it. With PyMOL’s built-in Python interpreter, repetitive actions are made simple.

Example 1: Print the names of all the selected objects

You’ve selected several objects in PyMOL, and you want to see their names. By default, a new selection object called “(sele)” is created. We can create a Python variable called seleobjs, say, and then loop over them:

seleobjs = cmd.get_object_list('(sele)')
for obj in seleobjs: print obj

Example 2: Disable all the selected objects

If you still have your selection, “(sele)”, you can disable them (effectively turn them off on the right-hand sidebar):

seleobjs = cmd.get_object_list('(sele)')
for obj in seleobjs: cmd.disable(obj)

Example 3: Delete all the selected objects

You’re done with the objects in your selection, “(sele)”: you might be able to delete them using “delete <wildcard>”, but if you can’t write a wildcard that covers all the names of the objects, you can iterate over a selection and delete them:

seleobjs = cmd.get_object_list('(sele)')
for obj in seleobjs: cmd.delete(obj)

Example 4: How to renumber residues with insertion codes in PyMOL

Here’s a more complicated example of iterating in PyMOL. Say we want to renumber the PyMOL object called “MOL_NAME”, which has residues with insertion codes to be renumbered, then, e.g.:

offset = 1000 # For proteins with fewer than 1000 residues, to avoid overwriting

# Remember to edit MOL_NAME in this code!

# Iterate over the α-carbons in chain B
resnums=[] ; iterate MOL_NAME and chain B and n. CA, resnums.append(resi)
for i,r in reversed(list(enumerate(resnums))): cmd.alter('/MOL_NAME//B/\%s/'  %  r, 'resi="%d"' % (i + offset))

# Iterate over the α-carbons in chain D
resnums=[] ; iterate MOL_NAME and chain D and n. CA, resnums.append(resi)
for i,r in reversed(list(enumerate(resnums))): cmd.alter('/MOL_NAME//D/\%s/'  %  r, 'resi="%d"' % (i + offset))

# Tell PyMOL to sort the atoms; this is necessary after altering
sort

Note that these for-loops are written on one line; you could also use the backslash ‘\’ to break the command over multiple lines.

Author