16
from itertools import product
teams = ['india', 'australia', 'new zealand']
word_and = ['and']
tmp = '%s %s %s'
items = [teams, word_and, teams]
print(list(tmp % a for a in list(product(*items))))

prints:

['india and india',
 'india and australia',
 'india and new zealand',
 'australia and india',
 'australia and australia',
 'australia and new zealand',
 'new zealand and india',
 'new zealand and australia',
 'new zealand and new zealand']

How to:

  1. avoid the same name repeating in a single sentence (india and india)
  2. generate only one combination (either india and australia or australia and india)

http://pythonfiddle.com/product-without-matching-duplicates

dreftymac
  • 31,404
  • 26
  • 119
  • 182
Raj
  • 22,346
  • 14
  • 99
  • 142

1 Answers1

32

You should use itertools.combinations like this

>>> from itertools import combinations
>>> teams = ['india', 'australia', 'new zealand']
>>> [" and ".join(items) for items in combinations(teams, r=2)]
['india and australia', 'india and new zealand', 'australia and new zealand']

But for this simple case, you can run two loops, like this

>>> ["%s and %s" % (t1, t2) for i, t1 in enumerate(teams) for t2 in teams[i + 1:]]
['india and australia', 'india and new zealand', 'australia and new zealand']
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • which one would be faster? the combination or the enumerate? – Raj Mar 28 '15 at 06:36
  • 1
    @emaillenin Okay, I ran a simple [timing test](http://ideone.com/oV7kTb) and it confirms that `combination` is faster, with your sample data-set. – thefourtheye Mar 28 '15 at 06:48
  • 5
    @emaillenin `combinations` is faster but not by much: http://repl.it/fu7 However, there is no reason to not use combinations. – Shashank Mar 28 '15 at 06:48
  • This logic holds good only if the list has no duplicates. If we make teams = ['india', 'australia', 'new zealand', 'india'], the output will have 'india and india' in it. – yrnr Aug 23 '22 at 09:34