possible pairings in a set

John Posner jjposner at snet.net
Sun Apr 5 03:01:08 CEST 2009

 >> Also, if my code is considered ugly or redundant by this community,
 >> can you make suggestions to clean it up?

Python is pretty mature: if you have a simple, generic problem, the chances
are that someone else has already solved it, packaging the solution in a
library (or "module"). For your job, the "itertools" module includes the
function "combinations":

    import itertools
    for comb in itertools.combinations([0,1,2,3], 2):
        print comb

(0, 1)
(0, 2)
(0, 3)
(1, 2)
(1, 3)
(2, 3)

Note that the output of itertools.combinations() is not a list but an
iterator. If you need the entire list, use the list() function to have the
iterator deliver all the goods at once:

    mylist = list(itertools.combinations([0,1,2,3], 2))

E-mail message checked by Spyware Doctor (
Database version: 5.12110

More information about the Python-list mailing list