Getting all possible combinations of list items

Paul Winkler slinkp23 at
Mon Sep 17 19:31:13 CEST 2001

On Mon, 17 Sep 2001 00:26:40 -0500, Greg Krohn <volucris at> wrote:
>Does anyone know of how I should go about generating a list whose keys are
>all the possible combinations of the items in another list?
>another_list = ['a', 'b', 'c']
>magic_algorithm(another_list) -> ['aa', 'ab', 'ac', 'ba', 'bc', 'bc', 'ca',
>'cb', 'cc']

Here's a simple one:

def magic_algorithm(alist):
    result = []
    for s in alist:
        result.extend([s + s2 for s2 in alist])
    return result

Or if you wanted to exclude duplicates (e.g. "aa", "bb", etc.):

def m(alist):
    """This version will not produce combinations like aa, bb, cc..."""
    result = []
    count = len(alist)
    for i in range(count):
        elsewhere = range(0, i) + range(i + 1, count)
        result.extend([alist[i] + alist[j] for j in elsewhere])
    return result


More information about the Python-list mailing list