-1

suppose I have a list in python that is

['hello', 'yo', 'great', 'this', 'cool', 'fam']

how do I get all the possible 2 combinations that I can have from this list in tuples; output example:

[ ('hello','hello'),('hello','yo'),('hello', 'great'),...,('yo','hello'),('yo', 'yo') .... ] 

and so on

no packages allowed

MoeNeuron
  • 78
  • 8

3 Answers3

0

You can have a look at https://docs.python.org/2/library/itertools.html#itertools.permutations, more specific to the class itertools.permutations(iterable[, r])

As soon as you have already a tuple and you just need the combinations of 2 elements you can edit the code like

n = len(my_tuple)
indices = range(n)
cycles = range(n, n-2, -1)
yield tuple(my_tuple[i] for i in indices[:2])
while n:
    for i in reversed(range(2)):
        cycles[i] -= 1
        if cycles[i] == 0:
            indices[i:] = indices[i+1:] + indices[i:i+1]
            cycles[i] = n - i
        else:
            j = cycles[i]
            indices[i], indices[-j] = indices[-j], indices[i]
            yield tuple(my_tuple[i] for i in indices[:2])
            break
    else:
        return

where my_tuple is the input tuple

NicoCaldo
  • 1,171
  • 13
  • 25
0

Well, the desired output is simply the result of the Cartesian product (pairs and order matter), so either you can try this here or by using list comprehension:

[(entry1, entry2) for entry1 in myList for entry2 in myList]

with myList is your input list.

MoeNeuron
  • 78
  • 8
0

Take the cartesian product between your list and itself:

l1 = [hello,yo,great,this,cool,fam]
l2 = [hello,yo,great,this,cool,fam]
l1_x_l2 = [(i1, i2) for i1 in l1 for i2 in l2]

or more simply just do

l = [hello,yo,great,this,cool,fam]
l_x_l = [(i1, i2) for i1 in l for i2 in l]
yldm
  • 144
  • 3
  • 14