Home > Net >  Itertools without repetition but with multiple combinations
Itertools without repetition but with multiple combinations

Time:09-13

i can't seem to find a way to use itertools without repetitions while keeping multiple combinations.

What I want :

> my_list = ['a', 'b', 'c']
> the_result_i_want = ['ab', 'ac', 'ba', 'bc', 'ca', 'cb']

What I manage to do so far :

for i in range (2, len(my_list)) : 
    for my_result in itertools.product(my_list, repeat=i) : 
        print(''.join(my_result))

but the result I currently have is aa ab ac ba bb bc ca cb cc
(i know it's a similar question to this but the answer considere that ab and ba are the same, which in my case should be different)
Thank you !

CodePudding user response:

The solution is one item below the documentation for itertools.product, namely itertools.permutations:

from itertools import permutations

print([''.join(item) for item in permutations(my_list, 2)])

gives

['ab', 'ac', 'ba', 'bc', 'ca', 'cb']
  • Related