Monica Monica - 9 months ago 41
Python Question

Creating pairs of objects in a list

I have a list of objects:

object_list = ['distance', 'alpha1', 'alpha2', 'gamma']

I want to obtain a new list with a pair combination of those objects, such as:

new_list = [ ['distance', 'alpha1'], ['distance', 'alpha2'], ['distance', 'gamma'],['alpha1', 'alpha2'], [ 'alpha1', 'gamma'] ... ]

Generally I will obtain 24 sublists(cases).


Have a look at itertools - itertools.combinations seems to be the thing you are looking for. use like

import itertools
object_list = ['distance', 'alpha1', 'alpha2', 'gamma']
new_list = list(itertools.combinations(object_list, 2))