0

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).

Monica
  • 1,030
  • 3
  • 17
  • 37
  • 4
    Possible duplicate of [Python code to pick out all possible combinations from a list?](http://stackoverflow.com/questions/464864/python-code-to-pick-out-all-possible-combinations-from-a-list) – niemmi Aug 05 '16 at 21:33

2 Answers2

1

itertools.combinations if order isn't important or itertools.permutations if order matters

itertools.combinations

>>> a = ['a', 'b', 'c']
>>> list(itertools.combinations(a, 2))
('a', 'b'), ('a', 'c'), ('b', 'c')]   # Order isn't important

itertools.permutations

>>> a = ['a', 'b', 'c']
>>> list(itertools.permutations(a, 2))
[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]  #Order matters
Asish M.
  • 2,588
  • 1
  • 16
  • 31
0

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))
janbrohl
  • 2,626
  • 1
  • 17
  • 15
  • I try to extend my task and use lists instead of strings. distance = ['3', '-3'] alpha1 = ['3', '-3'] alpha2 = ['3', '-3'] gamma = ['3', '-3'] Is there easy way to use lists instead of strings? – Monica Aug 06 '16 at 01:10
  • just set `object_list = [ ['3', '-3'], ['3', '-3'], ['3', '-3'], ['3', '-3']]` – janbrohl Aug 06 '16 at 07:03