0

I have the following code snippet that is quite inefficient: It aims to produce 27 different combinations of exactly 3 numbers for each combination

nums = [i for i in range(1,4)]
combinations = []
for i in nums:
  for j in nums:
    for k in nums:
      combinations.append([i,j,k])

This generates 27 combinations which is correct.

Is there a more efficient way to generate this and how can I store into a dataframe instead of a list ?

Roger Steinberg
  • 1,554
  • 2
  • 18
  • 46
  • not sure why this is tagged to another question. its definitely not the same – Roger Steinberg Nov 10 '21 at 01:01
  • @Selcuk you pointed to questions wanting `combinations` but Roger is clearly wanting `itertools.product` you should have pointed to https://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a-series-of-lists or similar – Tadhg McDonald-Jensen Nov 10 '21 at 01:02
  • @TadhgMcDonald-Jensen im not sure that its product because it wouldn't give me 27 combinations with a list of 3 numbers ( 3^3). – Roger Steinberg Nov 10 '21 at 01:06
  • 1
    `itertools.product(nums, repeat=3)` is what you are looking for, https://stackoverflow.com/questions/16384109/iterate-over-all-combinations-of-values-in-multiple-lists-in-python might have been a better target. – Tadhg McDonald-Jensen Nov 10 '21 at 01:09
  • @TadhgMcDonald-Jensen You are correct, updated the duplicate. Confused by the wording used in the question. – Selcuk Nov 10 '21 at 01:10
  • 1
    https://stackoverflow.com/questions/25634489/get-all-combinations-of-elements-from-two-lists is probably the best target as it is both asking for combinations (but meaning product) from lists and about `DataFrame`, It really bugs me how hard it is to find those existing questions even when you know what to look for just because "combinations" is used in plain english to mean both "cartesian product" and "mathematical sequence combinations" and occasionally permutations too. – Tadhg McDonald-Jensen Nov 10 '21 at 01:19

0 Answers0