Ask Your Question

Revision history [back]

First a remark: in addition to iteration by index, Python offers iteration by values.

Since it makes code much more natural and readable, using it is encouraged.

For instance, if things is a list, and f is a function, then among the following two equivalent lines,

sage: [f(v) for v in things]
sage: [f(things[i]) for i in range(len(things))]

we can hopefully agree the first one is not only more concise but clearer.

This might do what you want.

ww = ['AB', 'AC', 'AD', 'BC', 'BD', 'CD']
cond1 = ['${}-{}$'.format(*w) for w in ww]

First a remark: in addition to iteration by index, Python offers iteration by values.

Since it makes code much more natural and readable, using it is encouraged.

For instance, if things is a list, and f is a function, then among the following two equivalent lines,

sage: [f(v) for v in things]
sage: [f(things[i]) for i in range(len(things))]

we can hopefully agree the first one is not only more concise but clearer.

This might do what you want.

ww = ['AB', 'AC', 'AD', 'BC', 'BD', 'CD']
cond1 = ['${}-{}$'.format(*w) for w in ww]

With two {} placeholders in the string ${}-{}$', theformat` method expects two arguments.

This works:

sage: '${}-{}$'.format('A', 'B')
'$A-B$

But if we provide the two arguments in packed form, e.g. as a list, tuple, or string, we need to unpack them.

This is done with * which used as a prefix is the unpacking operator in Python.

sage: w = ['A', 'B']
sage: '${}-{}$'.format(w)  # index error
sage: '${}-{}$'.format(*w)  # good
'$A-B$

sage: w = 'AB'
sage: '${}-{}$'.format(w)  # index error
sage: '${}-{}$'.format(*w)  # good
'$A-B$