-1

I repost with a simplified question (my previous post was closed).

I need to output all combination of a list of length N.

I already know that combinations will do this with, as example, the actual input list: ['A, 'B'] ==> output: ['A', 'A'], ['A', 'B'], ['B', 'B']

But I need this: ['A', 'A'], ['A', 'B'], ['B', 'A'], ['B', 'B'].

Is there a way to do it with combinations()?

martineau
  • 119,623
  • 25
  • 170
  • 301
hexa
  • 15
  • 2
  • 3
    This looks like a [cartesian product](https://docs.python.org/3/library/itertools.html#itertools.product) to me. – BramAppel Dec 23 '19 at 00:20
  • 3
    `list(itertools.product('AB', repeat=2)) # [('A', 'A'), ('A', 'B'), ('B', 'A'), ('B', 'B')]` – Darkonaut Dec 23 '19 at 00:24
  • 1
    Does this answer your question? [How to generate all permutations of a list?](https://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list) – AMC Dec 23 '19 at 00:46
  • Wasn't your previous question a duplicate of https://stackoverflow.com/q/464864/11301900? What's different about this one? – AMC Dec 23 '19 at 01:09

2 Answers2

3

itertools.product is the tool for the job

>>> list(itertools.product('AB', repeat=2))
[('A', 'A'), ('A', 'B'), ('B', 'A'), ('B', 'B')]
Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50
1

You can use list comprehension:

all_combinations = [[x,y] for x in list_length_N for y in list_length_N]

Example with N=2

list_2 = [0,1]
all_combinations = [[x,y] for x in list_2 for y in list_2]
print(all_combinations)

Output:

[[0,0],[0,1],[1,0],[1,1]]
Luismi98
  • 282
  • 3
  • 14