Mubeen
Mubeen

Reputation: 98

Find all combinations of a list in python

The list that I have:

a = [1,2,3]

The output that I want:

combinations = [11, 12, 13, 21, 22, 23, 31, 32, 33]

I have tried:

a = [1,2,3]
all_combinations = []
list1_permutations = itertools.permutations(a, len(a))
for each_permutation in list1_permutations:
    zipped = zip(each_permutation, a)
    all_combinations.append(list(zipped))

print(all_combinations)

But I am getting the output like:

[[(1, 1), (2, 2), (3, 3)], [(1, 1), (3, 2), (2, 3)], [(2, 1), (1, 2), (3, 3)], [(2, 1), (3, 2), (1, 3)], [(3, 1), (1, 2), (2, 3)], [(3, 1), (2, 2), (1, 3)]]

Upvotes: 1

Views: 54

Answers (2)

Nick
Nick

Reputation: 147146

This might be easiest with a nested list comprehension:

a = [1, 2, 3]

out = [int(f'{i}{j}') for i in a for j in a]
print(out)

Output:

[11, 12, 13, 21, 22, 23, 31, 32, 33]

The same result can be achieved (perhaps more efficiently) with itertools.product:

import itertools

a = [1, 2, 3]
out = [int(f"{a}{b}") for a, b in itertools.product(a, a)]

Upvotes: 3

AirSquid
AirSquid

Reputation: 11883

This should work.

  • you can use a list comprehension to make all combos because you appear to want to sample with duplicates like '33'
  • you can use a list gen to do this
  • you need to treat the items like strings to join them
  • you need to convert it back to integer if that is what you want as final result

a=[1,2,3]

result = [int(''.join([str(i), str(j)])) for i in a for j in a]

print(result)

Upvotes: 1

Related Questions